1. leetcode24 两两交换链表中的节点
题目链接:24. 两两交换链表中的节点 - 力扣(LeetCode)
文章链接:代码随想录 (programmercarl.com)
视频链接:帮你把链表细节学清楚! | LeetCode:24. 两两交换链表中的节点_哔哩哔哩_bilibili
1.1 代码
这个代码是用循环的思路来进行判断的,写的过程挺考验中间赋值的
1.1.1 根据老师思路写的一个版本
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy_head = ListNode(next = head)
current =dummy_head
while (current.next and current.next.next):
temp = current.next
temp1 = current.next.next.next
current.next = current.next.next
current.next.next = temp
current.next.next.next = temp1
current = current.next.next
return dummy_head.next
1.1.2 根据python链式赋值的规律版本
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy_head = ListNode(next = head)
current =dummy_head
while (current.next and current.next.next):
current.next,current.next.next,current.next.next.next = current.next.next,current.next,current.next.next.next
current = current.next.next
return dummy_head.next
1.2 交换链表总结
- 思路上面就是链表的赋值的时候,他就是等于重新连接了,有的链条会因为重新连接而断开,所以对于断开的连接需要进行重连
- 思路上还有一点就是二者交换的时候,首先得保证这两个都是有数值的才能交换
2.leetcode19 删除链表的倒数第N个节点
题目链接:19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
文章链接:代码随想录 (programmercarl.com)
视频链接:链表遍历学清楚! | LeetCode:19.删除链表倒数第N个节点_哔哩哔哩_bilibili
2.1 代码
这道题就是看了觉得很简单,找到他的前一个值,然后进行删除,但是第一次写的时候就写错了,后面就重新看了别人的思路,写了一个版本
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy_head = ListNode(next = head)
current_fast = dummy_head
current_slow = dummy_head
for i in range(n+1):
current_fast = current_fast.next
while current_fast:
current_slow = current_slow.next
current_fast = current_fast.next
current_slow.next = current_slow.next.next
return dummy_head.next
2.2 总结
用到了双指针的快慢指针的思路,才开始想的太过简单,然后写的时候就废了,写错了,感觉今天的学习状态不佳,就先刷两道题,另一题明天再写吧。
标签:current,head,ListNode,self,随想录,next,链表,节点 From: https://www.cnblogs.com/csfy0524/p/18475970