zoukankan      html  css  js  c++  java
  • leetcode——19. 删除链表的倒数第N个节点

    用列表完成!!!!

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
            if head.next==None and n==1:
                return 
            a=[]
            while head:
                a.append(head.val)
                head=head.next
            #print(a)
            #print(len(a))
            a.pop(len(a)-n)
            head=ListNode(a[0])
            p=head
            for i in range(1,len(a)):
                p.next=ListNode(a[i])
                p=p.next
            return head
    执行用时 :44 ms, 在所有 python3 提交中击败了86.21%的用户
    内存消耗 :13.8 MB, 在所有 python3 提交中击败了5.53%的用户
     
                                                                                  ——2019.10.23
     

    public ListNode removeNthFromEnd(ListNode head, int n) {
            if(n == 0){
                return head;
            }
            if(n == 1 && head.next == null){
                return null;
            }
            if(n == 2 && head.next.next == null){
                return head.next;
            }
            ListNode dummy = new ListNode(-1);
            ListNode p = dummy;
            dummy.next = head;
            ListNode t = p;
            ListNode prev = p;
            while (n != 0){
                p = p.next;
                n--;
            }
            while (p != null){
                p = p.next;
                t = t.next;
                if(t != head){
                    prev = prev.next;
                }
            }
            prev.next = t.next;
            t.next = null;
            return dummy.next;
        }

    ——2020.7.14

    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    【Rust】文件操作
    【Rust】转义字符
    【Rust】原始标识符
    【Rust】字节数组
    【Rust】文档测试
    【Rust】外部函数接口
    【Rust】不安全操作
    【Rust】单元测试
    【Rust】集成测试
    WPF之ComboBox 安静点
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/11729556.html
Copyright © 2011-2022 走看看