给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
复制代码
1 /**
2 * Definition for singly-linked list.
3 * struct ListNode {
4 * int val;
5 * ListNode *next;
6 * ListNode(int x) : val(x), next(NULL) {}
7 * };
8 */
9 class Solution {
10 public:
11 ListNode* removeNthFromEnd(ListNode* head, int n) {
12 ListNode* first=head;
13 while(n–!=0)
14 first=first->next;
15 if(!first)
16 return head->next;
17 ListNode* sec=head;
18 while(first->next!=NULL){
19 sec=sec->next;
20 first=first->next;
21 }
22 sec->next=sec->next->next;
23 return head;
24 }
25 };