一、知识点介绍
二、例题
1.反转链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
p1,p2=head,None
while p1:
temp=p1.next
p1.next=p2
p2=p1
p1=temp
return p2
2.删除链表的倒数第 N 个结点
# 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: ListNode, n: int) -> ListNode:
p1=head
while n:
p1=p1.next
n-=1
p2=head
if not p1:
return p2.next
while p1.next:
p2=p2.next
p1=p1.next
p2.next=p2.next.next
return head
3.删除排序链表中的重复元素
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
p1,p2=head,head.next
while p2:
flag=0
while p2 and p1.val==p2.val:
p2=p2.next
flag=1
if flag:
p1.next=p2
if not p2:
break
p1=p2
p2=p2.next
return head
4.环形链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
if not head:
return False
p1=p2=head
while p1.next and p2.next and p2.next.next:
p1=p1.next
p2=p2.next.next
if p1==p2:
return True
return False
5.排序链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def findmid(self,head):
slow=fast=head
while fast.next and fast.next.next:
slow=slow.next
fast=fast.next.next
return slow
def merge(self,l,r):
head=ListNode(None)
cur=head
while l and r:
if l.val<=r.val:
cur.next=l
l=l.next
else:
cur.next=r
r=r.next
cur=cur.next
cur.next=l or r
return head.next
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
mid=self.findmid(head)
left=head
right=mid.next
mid.next=None
l=self.sortList(left)
r=self.sortList(right)
return self.merge(l,r)