力扣刷题-python-链表的操作(添加、删除、索引、交换、倒置)

1.链表的基础

python 是没有链表的,需要通过类函数来构建链表。
如下为力扣上链表定义

class ListNode(object):
     def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

2.移除链表

203. 移除链表元素 - 力扣(LeetCode) (leetcode-cn.com)
下面这段精髓在于,开始加了一个虚拟节点,后面怎么操作是后面的事情,开头不会再变了,排除了head.val等连续情况,减少了判断。
也不用加好几个指针,一个指之前,一个指之后,可以直接判断p.next.val,如果等于val,直接把,p.next=p.next.next 剩过很多赋值的过程。

class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """ 
        dummy_head = ListNode(next=head) #添加一个虚拟节点
        p=dummy_head

        while p.next!=None:
            if p.next.val== val:
                p.next=p.next.next
            else:
                p=p.next
        return dummy_head.next

3.设计链表(添加、索引、删除)

707. 设计链表 - 力扣(LeetCode) (leetcode-cn.com)

class ListNode(object):
     def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class MyLinkedList(object):
    def __init__(self):  #定义链表
        self._head=ListNode(0)  # 虚拟头部节点
        self._count=0           # 添加的节点数

    def get(self, index):  #获取链表的节点值
        """
        :type index: int
        :rtype: int
        """
        if 0<=index<self._count:
            p=self._head
            for _ in  range(index+1):p=p.next
            return p.val
        else:return -1                


    def addAtHead(self, val):#头部添加节点
        """
        :type val: int
        :rtype: None
        """
        self.addAtIndex(0, val)
    def addAtTail(self, val): #尾部添加节点
        """
        :type val: int
        :rtype: None
        """
        self.addAtIndex(self._count, val)

    def addAtIndex(self, index, val): #某索引处添加
        """
        :type index: int
        :type val: int
        :rtype: None
        """
        if index<0:index=0
        elif index> self._count: return 
        
        #计数累加
        self._count+= 1
        
        p=self._head
        for _ in range(index): p=p.next
        NewNode=ListNode(val,p.next)
        p.next=NewNode

    def deleteAtIndex(self, index): #某索引处删除
        """
        :type index: int
        :rtype: None
        """
        if 0<= index< self._count:
            #计数减一
            self._count-= 1

            p=self._head
            for _ in range(index):p=p.next
            p.next=p.next.next

# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)

4.翻转链表

https://tva1.sinaimg.cn/large/008eGmZEly1gnrf1oboupg30gy0c44qp.gif

# 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 reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """

        cur,pre= head,None
        while cur!=None:
          cur.next, cur, pre= pre, cur.next, cur  #同时
        return pre

5.两两交换链表中的节点

24. 两两交换链表中的节点 - 力扣(LeetCode) (leetcode-cn.com)
在这里插入图片描述

# 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
        """
        NewHead=ListNode(0,head)
        pre,cur= NewHead,NewHead.next

        while cur and cur.next:  #不为空
           cur= cur.next 
           pre.next, pre  =  cur, pre.next  #步骤1
           cur.next, cur  =  pre, cur.next  #步骤2
           pre.next  =  cur                 #步骤3

        return NewHead.next

6.删除链表的倒数第N个节点

19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode) (leetcode-cn.com)
在这里插入图片描述

# 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
        """
        Nhead= ListNode(0,head)
        slow =fast = Nhead
        while fast.next:
            n-= 1
            fast= fast.next
            if n<0:slow= slow.next
        slow.next=slow.next.next  #找到开始删除
        return Nhead.next

7.链表相交

面试题 02.07. 链表相交 - 力扣(LeetCode) (leetcode-cn.com)
在这里插入图片描述
盗用了别人算法,这个算法挺好用。。

# 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
        """
        """
        根据快慢法则,走的快的一定会追上走得慢的。
        在这道题里,有的链表短,他走完了就去走另一条链表,我们可以理解为走的快的指针。

        那么,只要其中一个链表走完了,就去走另一条链表的路。如果有交点,他们最终一定会在同一个
        位置相遇
        """
        curA, curB = headA, headB     # 用两个指针代替a和b

        
        while curA != curB:
            curA = curA.next if curA else headB      # 如果a走完了,那么就切换到b走
            curB = curB.next if curB else headA      # 同理,b走完了就切换到a
        
        return cur_a

8.环形链表

142. 环形链表 II - 力扣(LeetCode) (leetcode-cn.com)
1.是否为环形判断,用两个不同速度的指针,看是否为相遇,
在这里插入图片描述
2.找到入口,从相遇点和头节点分别放出指针,相遇点为入口。
在这里插入图片描述

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        slow=fast=head# 快速是2倍速 慢速是常速度

        while fast and fast.next and fast.next.next:
              slow= slow.next
              fast= fast.next.next
              if slow== fast:
                  p=head         #找到之后,从头节点,放出一个指针
                  while p!=slow: #和平常速度走的指针比较
                      p= p.next
                      slow= slow.next
                  return p
        return None

9.总结

快指针,慢指针,指针满天飞。。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值