24. Swap Nodes in Pairs
注意:
1. cur一定要指在要操作的node的前一个node
2. while(cur.next !=None and cur.next.next !=None)顺序不能反, 不然会空指针异常
这个终止条件的意思是若是偶数个node,则cur.next==None,若是奇数个node,则cur.next.next == None, 取反的话用and
3.用temp来提前记录断掉的node
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy_head = ListNode(next=head)
cur = dummy_head
while(cur.next!=None and cur.next.next!=None):
temp = cur.next
temp1 = cur.next.next.next
cur.next = cur.next.next
cur.next.next=temp
temp.next=temp1
cur= cur.next.next
return dummy_head.next
19. Remove Nth Node From End of List
注意:
1.用双指针fast和slow来找到倒数第n个节点,让fast和slow之间间隔n,这样当fast到null时slow正好到倒数第n
2.让slow指向倒数第n个节点的前一个,因此fast要走n+1步
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummy = ListNode(next=head)
slow = dummy
fast = dummy
n+=1
while(n and fast!=None):
fast = fast.next
n-=1
while(fast!=None):
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return dummy.next
160. Intersection of Two Linked Lists
注意这个intersection应该是指针重合而不是值相等
思路:数len,算两个len的差,将长的pointer移动此差值,然后一起向右移动直到找到intersection
【做题时先观察规律,两个linked lists的特点是末尾都相同】
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
lenA = 0
lenB = 0
curA = headA
curB = headB
while(curA!=None):
curA = curA.next
lenA+=1
while(curB!=None):
curB = curB.next
lenB+=1
curA = headA
curB = headB
if lenA > lenB:
for i in range(lenA-lenB):
curA = curA.next
while (curA!= None and curB != None and curA != curB):#有可能空指针异常
curA = curA.next
curB = curB.next
return curA
else:
for i in range(lenB-lenA):
curB = curB.next
while (curA!= None and curB != None and curA != curB):
curA = curA.next
curB = curB.next
return curB
return None
142. Linked List Cycle II
快慢指针法,数学推导详见代码随想录