LeetCode题解(19)--Remove Nth Node From End of List

 

 

 

 

 

 

 

 

https://leetcode.com/problems/remove-nth-node-from-end-of-list/

原题:

Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.



   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

 

思路:

考察指针的灵活使用。使用两个指针a和b就够了,中间间隔n个,一起向前移动,直到最后一个节点,然后删掉a->next。这样的算法需要注意删掉的是第一个节点的情况(也即不能是a->next了,直接head=head->next)。

 

我的AC代码:

 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 * to_remove, * p;

13         p=head;

14         for(int i=0;i<n;i++){

15             p=p->next;

16         }

17         if(p==NULL){

18             head=head->next;

19             return head;

20         }

21         to_remove=head;

22         while(p->next!=NULL){

23             p=p->next;

24             to_remove=to_remove->next;

25         }

26         to_remove->next=to_remove->next->next;

27         return head;

28     }

29 };

 

你可能感兴趣的:(LeetCode)