From 2ecb3669d05cff13b76a162b0185055b8cfecd79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= <14021051@buaa.edu.cn> Date: Tue, 18 Dec 2018 16:07:26 +0800 Subject: [PATCH] Create 19. Remove Nth Node From End of List.md --- 19. Remove Nth Node From End of List.md | 40 +++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 19. Remove Nth Node From End of List.md diff --git a/19. Remove Nth Node From End of List.md b/19. Remove Nth Node From End of List.md new file mode 100644 index 0000000..4e8a2d4 --- /dev/null +++ b/19. Remove Nth Node From End of List.md @@ -0,0 +1,40 @@ +# [19. Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) +# 思路 +题意就是去掉链表中倒数第n个节点。 +涉及到链表中倒数节点的思路都是使用两个指针p1、p2,两个指针初始都是head,p2先走n步,然后p1、p2再同时走直到p2到达链尾, +此时p1就位于链表倒数第n个节点的前一个节点。 +需要注意当要删除的节点就是head时需要特殊处理。 +时间复杂度O(N),空间复杂度O(1) + +# C++ +``` C++ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + if(n <= 0) return head; + ListNode *p1 = head, *p2 = head; + while(n--) p2 = p2 -> next; // p2先走n步 + if(p2 == NULL){ // 此时删掉的应该是head + head = head -> next; + delete p1; + return head; + } + while(p2 -> next){ + p1 = p1 -> next; + p2 = p2 -> next; + } // 此时p1位于倒数第n个节点的前一个节点 + p2 = p1 -> next; + p1 -> next = p2 -> next; + delete p2; + return head; + } +}; +```