链表基础知识对应的三道leetcode题

0707. 设计链表
0206.反转链表
0203. 移除链表元素

0707 设计链表

设计链表的实现。您可以选择使用单链表或双链表。单链表中的节点应该具有两个属性:val 和 next。val 是当前节点的值,next 是指向下一个节点的指针/引用。如果要使用双向链表,则还需要一个属性 prev 以指示链表中的上一个节点。假设链表中的所有节点都是 0-index 的。

在链表类中实现这些功能:

get(index):获取链表中第 index 个节点的值。如果索引无效,则返回-1。
addAtHead(val):在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点。
addAtTail(val):将值为 val 的节点追加到链表的最后一个元素。
addAtIndex(index,val):在链表中的第 index 个节点之前添加值为 val  的节点。如果 index 等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于链表长度,则不会插入节点。如果index小于0,则在头部插入节点。
deleteAtIndex(index):如果索引 index 有效,则删除链表中的第 index 个节点。
 

示例:

MyLinkedList linkedList = new MyLinkedList();
linkedList.addAtHead(1);
linkedList.addAtTail(3);
linkedList.addAtIndex(1,2);   //链表变为1-> 2-> 3
linkedList.get(1);            //返回2
linkedList.deleteAtIndex(1);  //现在链表是1-> 3
linkedList.get(1);            //返回3
 

提示:

所有val值都在 [1, 1000] 之内。
操作次数将在  [1, 1000] 之内。
请不要使用内置的 LinkedList 库。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/design-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

作者:azb-8

法1:规规矩矩写链表
源代码有点问题,改正了一下,可以通过测试

# 初始化节点,包含两个参数,val是节点值,next指向下一个节点
class Node:
    def __init__(self, val):
        self.val = val
        self.next = None


class MyLinkedList:
    # 初始化链表
    def __init__(self, node=None):
        '''
        Initialize your data structure here.
        '''
        # 如果链表输入链表第一个值,则将第一个节点设为链表节点
        if node != None:
            headNode = Node(node)
            self.__head = headNode
        # 如果还没有链表,则调用的时候,出现一个空链表
        else:
            self.__head = node

    # 根据要求:该函数获取链表中第index个节点的值。如果索引无效,则返回-1
    def get(self, index: int) -> int:
        '''
        Get the value of the index-th node in the linked list. If the index is invalid, return -1.
        '''
        count = 0
        cur = self.__head
        while cur:
            if count == index:
                return cur.val
            count += 1
            cur = cur.next
        return -1

    # 头插法
    def addAtHead(self, val: int) -> None:
        #将头节点设置为当前节点
        node = Node(val)
        node.next = self.__head
        self.__head = node

    # 尾插法
    def addAtTail(self, val: int) -> None:
        node = Node(val)
        # 判断,如果头节点为None,则将当前节点设置为头节点
        if self.__head == None:
            self.__head = node
        else:
            # 如果头结点不为None:遍历链表,知道最后一个节点
            cur = self.__head
            while cur.next != None:
                cur = cur.next
            #尾部插入
            cur.next = node

    # 指定位置插入
    def addAtIndex(self, index: int, val: int) -> None:
        node = Node(val)
        # 特色情况index<=0 则说明为头插法
        if index <= 0:
            self.addAtHead(val)
        elif index == self.length():
            self.addAtTail(val)
        elif index > self.length():
            return
        else:
            # 正常情况
            count = 0
            pre = self.__head
            while count < (index - 1):
                pre = pre.next
                count += 1
            node.next = pre.next
            pre.next = node

    # 删除指定节点
    def deleteAtIndex(self, index: int) -> None:
        # 判断特殊情况
        if index < 0 or index >=self.length():
            return
        # 如果为删除结点为头节点
        elif index == 0:
            self.__head = self.__head.next
        else:
            # 正常情况
            count = 0
            cur = self.__head
            while count < (index - 1):
                cur = cur.next
                count += 1
            cur.next = cur.next.next if cur.next is not None else None


    # 为了测试头插法和尾插法写的是否正确,自己写的一个遍历输出函数
    def bianli(self):
        cur = self.__head
        while cur:
            print(cur.val)
            cur = cur.next

    # 为了简化操作自己定义了计算链表长度的函数
    def length(self):
        count = 0
        cur = self.__head
        while cur:
            cur = cur.next
            count += 1
        return count

法2:巧用列表
直接维护一个列表

class MyLinkedList:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.linkedlist = []

    def get(self, index: int) -> int:
        """
        Get the value of the index-th node in the linked list. If the index is invalid, return -1.
        """
        if index < 0 or index >= len(self.linkedlist):
            a = -1
        else:
            a = self.linkedlist[index]
        return a

    def addAtHead(self, val: int) -> None:
        """
        Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
        """
        self.linkedlist.insert(0, val)

    def addAtTail(self, val: int) -> None:
        """
        Append a node of value val to the last element of the linked list.
        """
        self.linkedlist.append(val)

    def addAtIndex(self, index: int, val: int) -> None:
        """
        Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
        """
        if index < 0:
            self.linkedlist.insert(0, val)
        elif 0 <=index <= len(self.linkedlist):
            self.linkedlist.insert(index, val)

    def deleteAtIndex(self, index: int) -> None:
        """
        Delete the index-th node in the linked list, if the index is valid.
        """
        if 0 <= index < len(self.linkedlist):
            del self.linkedlist[index]

作者:azb-8
链接:https://leetcode-cn.com/problems/design-linked-list/solution/liang-chong-jie-fa-gui-gui-ju-ju-xie-lia-vezj/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

0206 反转链表

你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
提示:
链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000

迭代

作者:rocky0429-2写的挺好的,学习了。此方法为迭代,点击此处可以看看视频讲解

# 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 head.next == None:
            return head

        # 初始化记录当前节点 p 和前驱节点 q
        p = head
        q = None

        while p:
            temp = p.next
            p.next = q
            q = p
            p = temp
            
        # 最后一步,p 肯定是指向 NULL,所以返回 q 作为新的头指针
        return q

作者:rocky0429-2
链接:https://leetcode-cn.com/problems/reverse-linked-list/solution/acm-xuan-shou-tu-jie-leetcode-fan-zhuan-tz1m9/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

递归,参考

# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if head is None or head.next is None:
            return head
        
        p = self.reverseList(head.next)
        head.next.next = head
        head.next = None

        return p

0203. 移除链表元素

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
示例 1:
输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]
示例 2:
输入:head = [], val = 1
输出:[]
示例 3:
输入:head = [7,7,7,7], val = 7
输出:[]
提示:
列表中的节点数目在范围 [0, 104] 内
1 <= Node.val <= 50
0 <= val <= 50

自己写的,总感觉很陈余狼狈

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        # 如果是个空链表直接返回本身
        if head is None:
            return head
        # 首先有一个如果前面几个结点删除了,head结点应该后移的问题
        while head.val == val:
            head = head.next
            if head is None:
                return head
        p = head
        while p:
            if p.next is None:
                return head
            if p.next.val == val:
                p.next = p.next.next
            else:
                p = p.next
        return head

学习一下别人的

递归

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        if not head: return 
        head.next = self.removeElements(head.next, val)
        return head.next if head.val == val else head

迭代,和自己的大同小异,学习了

class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        while head and head.val == val:
            head = head.next
        if not head: return
        pre = head
        while pre.next:
            if pre.next.val == val:
                pre.next = pre.next.next
            else:
                pre = pre.next
        return head

双指针

  • 设置两个指针分别指向头节点,pre (记录待删除节点的前一节点)和 cur (记录当前节点);
  • 遍历整个链表,查找节点值为 val 的节点,找到了就删除该节点,否则继续查找。
  • 找到,将当前节点的前一节点(之前最近一个值不等于 val 的节点)连接到当前节点(cur 节点)的下一个节点(pre->next =
    cur->next)。
  • 没找到,更新最近一个值不等于 val 的节点(pre = cur),继续遍历(cur = cur->next)。
class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        while head and head.val == val:
            head = head.next
        pre, cur = head, head
        while cur:
            if cur.val == val:
                pre.next = cur.next
            else:
                pre = cur
            cur = cur.next
            
        return head

猜你喜欢

转载自blog.csdn.net/qq_44941689/article/details/122447817