首页 > 代码库 > 【LeetCode】Remove Nth Node From End of List

【LeetCode】Remove Nth Node From End of List

给定一个链表,删除从链表尾数起第n个节点,并返回头节点。

e.g. 

给定链表:1 -> 2 -> 3 -> 4 -> 5,n = 2

删除倒数第二个节点后的链表: 1 -> 2 -> 3 -> 5

 

我的笨方法:

原理是判断要删除的节点为从头数起第 count 个节点,然后判断是否为头节点,进行删除。

 1     int length(ListNode* head) {
 2         int n = 0;
 3         ListNode *p = head;
 4         while (p) {
 5             p = p -> next;
 6             n++;
 7         }
 8         return n;
 9     }
10     
11     ListNode* removeNthFromEnd(ListNode* head, int n) {
12         int count = length(head) - n + 1;
13         if (count == 1) {
14             ListNode *p = head;
15             head = head -> next;
16             delete p;
17         } else if (count-- > 1) {
18             ListNode *p = head, *q;
19             while (count) {
20                 q = p;
21                 p = p -> next;
22                 count--;
23             }
24             q -> next = p -> next;
25             delete p;
26         }
27         return head;
28     }

 

【LeetCode】Remove Nth Node From End of List