• [Swift]LeetCode707. 设计链表 | Design Linked List


    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
    ➤微信公众号:山青咏芝(shanqingyongzhi)
    ➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
    ➤GitHub地址:https://github.com/strengthen/LeetCode
    ➤原文地址: https://www.cnblogs.com/strengthen/p/10506371.html 
    ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
    ➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

    Design your implementation of the linked list. You can choose to use the singly linked list or the doubly linked list. A node in a singly linked list should have two attributes: val and nextvalis 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 these functions in your linked list class:

    • get(index) : Get the value of the index-th node in the linked list. If the index is invalid, return -1.
    • addAtHead(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.
    • addAtTail(val) : Append a node of value val to the last element of the linked list.
    • addAtIndex(index, val) : 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.
    • deleteAtIndex(index) : Delete the index-th node in the linked list, if the index is valid.

    Example:

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

    Note:

    • All values will be in the range of [1, 1000].
    • The number of operations will be in the range of [1, 1000].
    • Please do not use the built-in LinkedList library.

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

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

    • get(index):获取链表中第 index 个节点的值。如果索引无效,则返回-1
    • addAtHead(val):在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点。
    • addAtTail(val):将值为 val 的节点追加到链表的最后一个元素。
    • addAtIndex(index,val):在链表中的第 index 个节点之前添加值为 val  的节点。如果 index 等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于链表长度,则不会插入节点。
    • 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

    提示:

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

    Runtime: 168 ms
    Memory Usage: 19.3 MB
     1 class MyLinkedList {
     2     var list:[Int] = [Int].init()
     3     /** Initialize your data structure here. */
     4     init() {
     5         
     6     }
     7     
     8     /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
     9     func get(_ index: Int) -> Int {
    10        if list.count > index {
    11            return list[index]
    12        }
    13         return -1
    14     }
    15     
    16     /** 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. */
    17     func addAtHead(_ val: Int) {
    18         if list.count > 0 {
    19             list.insert(val,at:0)
    20         } else {
    21             list.append(val)
    22         }
    23     }
    24     
    25     /** Append a node of value val to the last element of the linked list. */
    26     func addAtTail(_ val: Int) {
    27         list.append(val)
    28     }
    29     
    30     /** 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. */
    31     func addAtIndex(_ index: Int, _ val: Int) {
    32         if list.count > index {
    33             list.insert(val,at:index)
    34         } else if list.count == index {
    35             list.append(val)
    36         }
    37     }
    38     
    39     /** Delete the index-th node in the linked list, if the index is valid. */
    40     func deleteAtIndex(_ index: Int) {
    41         if list.count > index {
    42             list.remove(at:index)
    43         }
    44     }
    45 }
    46 
    47 /**
    48  * Your MyLinkedList object will be instantiated and called as such:
    49  * let obj = MyLinkedList()
    50  * let ret_1: Int = obj.get(index)
    51  * obj.addAtHead(val)
    52  * obj.addAtTail(val)
    53  * obj.addAtIndex(index, val)
    54  * obj.deleteAtIndex(index)
    55  */

    196ms

     1 class MyLinkedList {
     2  
     3     var list = [Int]()
     4 
     5     /** Initialize your data structure here. */
     6     init() {
     7            
     8     }
     9     
    10     /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
    11     func get(_ index: Int) -> Int {
    12       if index < list.count {
    13           return list[index]
    14       }
    15 
    16       return -1
    17     }
    18     
    19     /** 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. */
    20     func addAtHead(_ val: Int) {
    21       list.insert(val, at: 0)
    22     }
    23     
    24     /** Append a node of value val to the last element of the linked list. */
    25     func addAtTail(_ val: Int) {
    26       list.append(val)
    27     }
    28     
    29     /** 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. */
    30      func addAtIndex(_ index: Int, _ val: Int) {
    31         if index <= list.count {
    32             list.insert(val, at: index)
    33         }
    34     }
    35     
    36     /** Delete the index-th node in the linked list, if the index is valid. */
    37     func deleteAtIndex(_ index: Int) {
    38       if index < list.count {
    39           list.remove(at: index)
    40       }
    41     }
    42 }

    216ms

      1 class MyLinkedList {
      2 
      3     private var count: Int = 0
      4     private var head: Node? = nil
      5     private var tail: Node? = nil
      6     
      7     init() {
      8         
      9     }
     10     
     11     public func get(_ index: Int) -> Int {
     12         return _get(index)?.val ?? -1
     13     }
     14     
     15     private func _get(_ index: Int) -> Node? {
     16         var curr = head
     17         
     18         for _ in 0..<index {
     19             curr = curr?.next
     20         }
     21         
     22         return curr
     23     }
     24     
     25     public func addAtHead(_ val: Int) {
     26         let node = Node()
     27         node.val = val
     28         
     29         if head == nil {
     30             head = node
     31             tail = node
     32         } else {
     33             node.next = head
     34             head?.prev = node
     35             head? = node
     36         }
     37         
     38         count += 1
     39     }
     40     
     41     public func addAtTail(_ val: Int) {
     42         let node = Node()
     43         node.val = val
     44         
     45         if head == nil {
     46             head = node
     47             tail = node
     48         } else {
     49             node.prev = tail
     50             tail?.next = node
     51             tail = node
     52         }
     53         
     54         count += 1
     55     }
     56     
     57     public func addAtIndex(_ index: Int, _ val: Int) {
     58         guard index <= count else { return }
     59         if index == 0 {
     60             addAtHead(val)
     61         } else if index >= count {
     62             addAtTail(val)
     63         } else {
     64             let node = _get(index - 1)
     65             let new = Node()
     66             new.val = val
     67             
     68             new.next = node?.next
     69             new.next?.prev = new
     70             new.prev = node
     71             node?.next = new
     72             
     73             count += 1
     74         }
     75     }
     76     
     77     public func deleteAtIndex(_ index: Int) {
     78         guard index < count else { return }
     79         if index == 0 {
     80             let node = head!
     81             if tail === node {
     82                 tail = nil
     83             }
     84             head = node.next
     85             head?.prev = nil
     86             node.next = nil
     87         } else if index >= count - 1 {
     88             let node = tail!
     89             tail = tail?.prev
     90             tail?.next = nil
     91             node.prev = nil
     92         } else {
     93             let node = _get(index)
     94             node?.prev?.next = node?.next
     95             node?.next?.prev = node?.prev
     96         }
     97         count -= 1
     98     }
     99     
    100     private class Node {
    101         var val: Int = 0
    102         var next: Node? = nil
    103         var prev: Node? = nil
    104     }
    105 }

    224ms

      1 class MyLinkedList {
      2     
      3     private class Node {
      4         var next: Node?
      5         var prev: Node?
      6         var val: Int
      7         
      8         init(_ val: Int, next: Node? = nil, prev: Node? = nil) {
      9             self.val = val
     10             self.next = next
     11             self.prev = prev
     12         }
     13     }
     14     
     15     private var head: Node?
     16     private var tail: Node?
     17     var count = 0
     18     var isEmpty: Bool {
     19         return count == 0
     20     }
     21     
     22     /** Initialize your data structure here. */
     23     init() {
     24         
     25     }
     26     
     27     /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
     28     func get(_ index: Int) -> Int {
     29         guard index >= 0, index < self.count else {return -1}
     30         return getNodeForIndex(index).val
     31     }
     32     
     33     /** 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. */
     34     func addAtHead(_ val: Int) {
     35         guard let head = head else {
     36             self.head = Node(val)
     37             self.tail = self.head
     38             self.count += 1
     39             return
     40         }
     41         let newHead = Node(val, next: head, prev: nil)
     42         head.prev = newHead
     43         self.head = newHead
     44         self.count += 1
     45     }
     46     
     47     /** Append a node of value val to the last element of the linked list. */
     48     func addAtTail(_ val: Int) {
     49         guard let tail = tail else {
     50             self.head = Node(val)
     51             self.tail = self.head
     52             self.count += 1
     53             return
     54         }
     55         let newTail = Node(val, next: nil, prev: tail)
     56         tail.next = newTail
     57         self.tail = newTail
     58         self.count += 1
     59     }
     60     
     61     /** 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. */
     62     func addAtIndex(_ index: Int, _ val: Int) {
     63         guard index >= 0, index <= self.count else { return }
     64         guard index != 0 else {
     65             addAtHead(val)
     66             return
     67         }
     68         guard index != self.count else {
     69             addAtTail(val)
     70             return
     71         }
     72         let current = getNodeForIndex(index - 1)
     73         let newNode = Node(val, next: current.next, prev: current)
     74         current.next = newNode
     75         newNode.next?.prev = newNode
     76         self.count += 1
     77     }
     78     
     79     /** Delete the index-th node in the linked list, if the index is valid. */
     80     func deleteAtIndex(_ index: Int) {
     81         guard index >= 0, index < self.count else { return }
     82         guard self.count > 1 else {
     83             self.head = nil
     84             self.tail = nil
     85             self.count -= 1
     86             return
     87         }
     88         guard index != 0 else {
     89             self.head = self.head?.next
     90             self.head?.prev = nil
     91             self.count -= 1
     92             return
     93         }
     94         guard index != self.count - 1 else {
     95             self.tail = self.tail?.prev
     96             self.tail?.next = nil
     97             self.count -= 1
     98             return
     99         }
    100         let current = getNodeForIndex(index)
    101         let prev = current.prev!
    102         let next = current.next!
    103         prev.next = next
    104         next.prev = prev
    105         self.count -= 1
    106     }
    107     
    108     private func getNodeForIndex(_ index: Int) -> Node {
    109         if index < self.count / 2 {
    110             var current = self.head!
    111             for _ in 0..<index {
    112                 current = current.next!
    113             }
    114             return current
    115         } else {
    116             var current = self.tail!
    117             var i = self.count - 1
    118             while i > index {
    119                 current = current.prev!
    120                 i -= 1
    121             }
    122             return current
    123         }
    124     }
    125 }

    328ms

      1 class MyLinkedList {
      2     
      3     var head: ListNode?
      4     var tail: ListNode?
      5     var size: Int
      6     
      7     init(){
      8         self.size = 0
      9     }
     10     
     11     func get(_ index: Int) -> Int {
     12         
     13         if  index >= size {
     14             return -1;
     15         }
     16         
     17         var tempNode = head
     18         var i = 0
     19         while i < index {
     20             tempNode = tempNode?.next
     21             i += 1
     22         }
     23         
     24         return tempNode!.val
     25     }
     26     
     27     func addAtHead(_ val: Int){
     28         
     29         let node = ListNode(val)
     30         node.next = head
     31         head = node
     32         
     33         if tail == nil {
     34             tail = head
     35         }
     36         size += 1
     37     }
     38     
     39     func addAtTail(_ val: Int){
     40         let node = ListNode(val)
     41         if let tail = tail {
     42             tail.next = node
     43          }else {
     44             head = node
     45         }
     46         
     47         tail = node
     48         size += 1
     49         
     50         
     51     }
     52     
     53     func addAtIndex(_ index:Int, _ val: Int){
     54         
     55         if (index > self.size){
     56             return
     57         }
     58         
     59         if(index == self.size){
     60             self.addAtTail(val)
     61             return
     62         }
     63         
     64         if (index == 0) {
     65             self.addAtTail(val)
     66             return
     67         }
     68         
     69         
     70         //需要两个节点--插入位置的前结点,和插入位置的后(现)结点
     71         //index 位置前面的结点
     72         var tempNode = head
     73         var i = 0
     74         while i < index-1 {
     75             tempNode = tempNode?.next
     76             i += 1
     77         }
     78         
     79         let nextNode = tempNode?.next
     80         
     81         let node = ListNode(val)
     82         tempNode?.next = node
     83         node.next = nextNode
     84         
     85         size += 1
     86     }
     87     
     88     func deleteAtIndex(_ index:Int) {
     89         
     90         if index >= size {
     91             return;
     92         }
     93         
     94         if(index == 0){
     95             if(size == 1){
     96                 size = 0
     97                 head = nil
     98                 tail = nil
     99             }
    100             head = head?.next
    101             size -= 1
    102             return;
    103         }
    104         
    105         var tempNode = head
    106         
    107         for _ in 0..<index-1{
    108             tempNode = tempNode?.next
    109         }
    110         
    111         if index == size - 1{
    112             tail = tempNode
    113             tail?.next = nil
    114             size -= 1
    115             return;
    116         }
    117         
    118         let nextNode = tempNode?.next?.next
    119         tempNode?.next = nextNode
    120         size -= 1        
    121     }
    122 }
  • 相关阅读:
    java 支付宝即时到帐提交订单dome
    C#字符串string的常用使用方法(转载)
    UltraEdit 回车符替换空格
    java 七牛上传图片到服务器(采用的html5 压缩 传输base64方式)
    c# 多播委托
    c# 泛型委托
    c# 求数组的最大值
    c# 匿名函数和lamda表达式语法
    匿名函数和lamda表达式
    导出Excel之Epplus使用教程4(其他设置)
  • 原文地址:https://www.cnblogs.com/strengthen/p/10506371.html
Copyright © 2020-2023  润新知