第一题
本题心得:
1、一定要判断是 是否定条件还是肯定条件。
肯定条件:画出临界成立情况的指针位置,写出成立条件,判断临界不成立情况
否定条件:画出临界不成立情况,写出否定条件
2.当链表顺序改变时,改变的箭头尾部元素要记录
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(0,next=head)
cur=dummy_head
while cur.next and cur.next.next:
temp=cur.next #原本链接的需要存起来
temp1=cur.next.next.next #原本链接的需要存起来
cur.next=cur.next.next
cur.next.next=temp
cur.next.next.next=temp1
cur= cur.next.next
return dummy_head.next
题目二
快慢指针法
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_head=ListNode(0,next=head)
fast=head
slow=dummy_head
size=0
while fast:
size+=1
fast=fast.next
for i in range(size-n):
slow=slow.next
slow.next=slow.next.next
return dummy_head.next
第三题:
求出两个列表长度差n,将较长链表的头指针位置移动n隔位置,然后两个链表同时遍历,判断相等条件
第四题:
fast指针每次移动2个,slow指针每次移动1个。两个指针必定能够在环内相遇。当 相遇时,设置index1和index2,同时移动,相遇位置即为环的入口。
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
fast=head
slow=head
while fast and fast.next:
fast=fast.next.next
slow=slow.next
if fast==slow:
index1= fast
index2= head
while index1!=index2:
index1=index1.next
index2=index2.next
return index2
return None