删除链表中的节点
class Solution:
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
cur = node
while cur.next.next != None:
cur.val = cur.next.val
cur = cur.next
cur.val = cur.next.val
cur.next = None
删除链表的倒数第N个节点
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if head.next is None:
head = None
return
pre = head
cur = head
count = 1
while cur.next != None:
cur = cur.next
count += 1
if count > n+1:
pre = pre.next
if count == n:
head = head.next
else:
pre.next = pre.next.next
return head
反转链表
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None or head.next == None:
return head
stern = head.next
new_head = self.reverseList(stern)
head.next = None
stern.next = head
return new_head
合并两个有序链表
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
cur1 = l1
cur2 = l2
head = ListNode(0)
cur3 = head
while cur1 != None and cur2 != None:
if cur1.val > cur2.val:
cur3.next = cur2
cur2 = cur2.next
else:
cur3.next = cur1
cur1 = cur1.next
cur3 = cur3.next
if cur1 is None:
cur3.next = cur2
else:
cur3.next = cur1
return head.next
回文链表
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None or head.next == None:
return head
stern = head.next
new_head = self.reverseList(stern)
head.next = None
stern.next = head
return new_head
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head is None or head.next is None:
return True
cur_s = head
cur_f = head
while cur_f.next != None and cur_f.next.next != None:
cur_f = cur_f.next.next
cur_s = cur_s.next
cur_s_next = cur_s.next
cur_s.next = self.reverseList(cur_s_next)
cur_s = cur_s.next
cur = head
while cur_s != None:
if cur.val != cur_s.val:
return False
else:
cur = cur.next
cur_s = cur_s.next
return True
环形链表
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head is None:
return False
cur_s = head
cur_f = head.next
while cur_s != cur_f and cur_f != None and cur_f.next != None:
cur_s = cur_s.next
cur_f = cur_f.next.next
if cur_s == cur_f:
return True
else:
return False