代码随想录算法训练营第3天| 203.移除链表元素 707.设计链表 206.反转链表

链表理论基础 

文章链接:代码随想录

203.移除链表元素 

题目链接:Remove Linked List Elements - LeetCode

文章讲解/视频讲解::代码随想录

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

Example 1:

Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]

Example 2:

Input: head = [], val = 1
Output: []

Example 3:

Input: head = [7,7,7,7], val = 7
Output: []

解题思路:

看见linklist先设置dummyhead

设置cur=dummyhead

当cur.next存在时看是否他的val等于目标值,如果等于那就需要解除链表。 解除链表是要将cur.next.next接到cur.next, 要注意的是如果我们直接接的话会导致cur.next后面的链表仍然接着它, 所以我们先保留cur.next.next,然后解除cur.next后面的链表,才重新接cur。如果不等于的话循环直接走cur=cur.next

# 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 removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        fk_head = ListNode(None)
        fk_head.next = head
        cur = fk_head
        while cur.next:
            if cur.next.val == val:
                nxt=cur.next.next
                cur.next.next=None
                cur.next=nxt
            else:
                cur=cur.next
        return fk_head.next
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)

707.设计链表 

题目链接:Design Linked List - LeetCode

题目链接/文章讲解/视频讲解:代码随想录

Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: val and nextval is the value of the current node, and next is a pointer/reference to the next node.
If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed.

Implement the MyLinkedList class:

  • MyLinkedList() Initializes the MyLinkedList object.
  • int get(int index) Get the value of the indexth node in the linked list. If the index is invalid, return -1.
  • void addAtHead(int val) 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.
  • void addAtTail(int val) Append a node of value val as the last element of the linked list.
  • void addAtIndex(int index, int val) Add a node of value val before the indexth node in the linked list. If index equals the length of the linked list, the node will be appended to the end of the linked list. If index is greater than the length, the node will not be inserted.
  • void deleteAtIndex(int index) Delete the indexth node in the linked list, if the index is valid.

Example 1:

Input
["MyLinkedList", "addAtHead", "addAtTail", "addAtIndex", "get", "deleteAtIndex", "get"]
[[], [1], [3], [1, 2], [1], [1], [1]]
Output
[null, null, null, null, 2, null, 3]

Explanation
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.addAtHead(1);
myLinkedList.addAtTail(3);
myLinkedList.addAtIndex(1, 2);    // linked list becomes 1->2->3
myLinkedList.get(1);              // return 2
myLinkedList.deleteAtIndex(1);    // now the linked list is 1->3
myLinkedList.get(1);              // return 3

解题思路:

暴力解题:

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

class MyLinkedList(object):
    def __init__(self):
        self.head = None
        self.size = 0
        

    def get(self, index):
        """
        :type index: int
        :rtype: int
        """
        if index<0 or index>=self.size:
            return -1
        cur=self.head
        for i in range(index):
            cur=cur.next
        return cur.val
            
        

    def addAtHead(self, val):
        """
        :type val: int
        :rtype: None
        """
        if self.size == 0:
            self.head = LinkNode(val)
        else:
            new_node=LinkNode(val)
            new_node.next=self.head
            self.head=new_node
        self.size+=1

        

    def addAtTail(self, val):
        """
        :type val: int
        :rtype: None
        """
        if self.size == 0:
            self.addAtHead(val)
        else:
            cur=self.head
            while cur.next:
                cur=cur.next
            cur.next=LinkNode(val)
            self.size+=1


        

    def addAtIndex(self, index, val):
        """
        :type index: int
        :type val: int
        :rtype: None
        """
        if index <= 0:
            self.addAtHead(val)
            return
        elif index == self.size:
            self.addAtTail(val)
            return
        elif index > self.size:
            return
        else:
            pre = None
            cur= self.head
            for i in range(index):
                pre=cur
                cur=cur.next
            new_node=LinkNode(val)
            new_node.next=cur
            pre.next=new_node
            self.size+=1
            



        

    def deleteAtIndex(self, index):
        """
        :type index: int
        :rtype: None
        """
        if index < 0 or index >=self.size:
            return
        elif index == 0:
            self.head=self.head.next
            self.size-=1
        elif index == self.size-1:
            pre=None
            cur=self.head
            for i in range(index):
                pre=cur
                cur=cur.next
            pre.next=None
            self.size-=1
        else:
            pre=None
            cur=self.head
            for i in range(index):
                pre=cur
                cur=cur.next
            pre.next=cur.next
            self.size-=1



        


# 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)

dummy_head.

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

class MyLinkedList(object):

    def __init__(self):
        self.head = Node()
        self.size = 0
        

    def get(self, index):
        """
        :type index: int
        :rtype: int
        """
        if index < 0 or index >= self.size:
            return -1
        cur = self.head.next
        for i in range(index):
            cur = cur.next
        return cur.val
        

    def addAtHead(self, val):
        """
        :type val: int
        :rtype: None
        """
        new_node = Node(val)
        new_node.next = self.head.next
        self.head.next = new_node
        self.size += 1
        

    def addAtTail(self, val):
        """
        :type val: int
        :rtype: None
        """
        new_node = Node(val)
        cur = self.head
        while(cur.next):
            cur = cur.next
        cur.next = new_node
        self.size += 1
        

    def addAtIndex(self, index, val):
        """
        :type index: int
        :type val: int
        :rtype: None
        """
        if index < 0:
            return
        elif index == self.size:
            self.addAtTail(val)
            return
        elif index > self.size:
            return

        node = Node(val)
        pre = self.head
        for i in range(index):
            pre = pre.next
        node.next = pre.next
        pre.next = node
        self.size += 1
        

    def deleteAtIndex(self, index):
        """
        :type index: int
        :rtype: None
        """
        if index < 0 or index >= self.size:
            return
        pre = self.head
        for i in range(index):
            pre = pre.next
        pre.next = pre.next.next
        self.size -= 1
        


# 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)

206.反转链表 

Reverse Linked List - LeetCode

题目链接/文章讲解/视频讲解:代码随想录

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2:

Input: head = [1,2]
Output: [2,1]

Example 3:

Input: head = []
Output: []

解题思路:

双指针pre 和 cur

cur指针指向head,pre指针指向前一个(初始值为None)

进入循环,条件为while cur因为如果while cur.next我们会少跑最后一个链表。 

当我们要将cur指向pre时会发现会失去原先对next的链接,所以先设一个值temp来保留cur.next, 然后再将cur指向pre。 此时我们要移动pre和cur,将cur赋值给pre,temp赋值给cur继续循环。 

# 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=head
        pre= None
        while cur:
            nxt=cur.next
            cur.next=pre
            pre=cur
            cur=nxt
        return pre
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值