[leetcode]移除链表尾端第n个结点


Given a linked list, remove the n-th node from the end of list and return its head.
给定链接列表,从列表末尾删除第n个节点并返回其头部。

一.c++代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
using namespace std;
//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) {
int length1=1;
ListNode* p = head;
ListNode* q = head;

while (p->next)
{
length1++;
p = p->next;

}
int cha = length1 - n;
//if (length1 == 1)
// return NULL;

if (length1 <= n)
head = head->next;
else
{
for (int i = 0; i < (cha - 1); i++)
{
q = q->next;
}
ListNode *t = q->next;
q->next = t->next;
delete t;
}
return head;
}
};

测试结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main() {

/*Solution *s;*/
ListNode* l1 = new ListNode(1);
ListNode *l11 = l1;
l11->next = new ListNode(2);
l11 = l11->next;
l11->next = new ListNode(3);
l11 = l11->next;
l11->next = new ListNode(4);
l11 = l11->next;
l11->next = new ListNode(5);
Solution* s = new Solution;
s->removeNthFromEnd(l1, 1);
system("pause");
return 0;
}