链表
- 链表的移动、翻转
- 链表的插入与删除
- 链表形状的判断
链表的移动与翻转
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
q = ListNode(0)
node = q
q.next = head
cur = head
while cur and cur.next:
p = cur.next
q.next = p
cur.next = p.next
q = cur
p.next = cur
cur = cur.next
return node.next
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if head == None:
return None
if k == 0:
return head
cur = head
node = head
length = 0
while cur:
if cur.next:
cur = cur.next
length += 1
else:
length += 1
break
if k > length:
k = k % length
if k == length:
return head
tmp = length - k
while tmp > 1:
node = node.next
tmp -= 1
cur.next = head
head = node.next
node.next = None
return head
链表的插入与删除
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
cur = head
while cur and cur.next:
if cur.val == cur.next.val:
cur.next = cur.next.next
else:
cur = cur.next
return head
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
fast = head
slow = head
while n > 0:
fast = fast.next
n -= 1
if fast == None:
return head.next
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return head
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l3 = ListNode(0)
head = l3
cur1 = l1
cur2 = l2
while cur1 and cur2:
if cur1.val <= cur2.val:
node = ListNode(cur1.val)
l3.next = node
l3 = l3.next
cur1 = cur1.next
else:
node = ListNode(cur2.val)
l3.next = node
l3 = l3.next
cur2 = cur2.next
if cur1:
l3.next = cur1
else:
l3.next = cur2
return head.next
链表形状的判断
方法一:置空法
遍历链表,每走到一个结点将其值置为None,在遍历的过程中,若遍历到的结点值为空,说明这个结点已经遍历过一次,说明这个链表为环形链表
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
cur = head
while cur:
if cur.val == None:
return True
cur.val = None
cur = cur.next
return False
方法二:快慢指针法
设置快指针和慢指针,快指针在慢指针的后一个结点,快指针每次走两步,慢指针每次走一步,当快指针超过慢指针时,说明链表是环形链表
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head == None:
return False
fast = head.next
slow = head
while slow != fast:
if fast == None or fast.next == None:
return False
fast = fast.next.next
slow = slow.next
return True