【LeetCode】19. 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.

题意:给出一个链表,删除倒数第n个节点

刚在书上见过这个题,思路是用双指针,p1,p2,先让p2走n步,然后p1,p2一块走,当p2停止的时候,

p1->next正好指向要删除的节点,不过要注意:

当p2停止的时候,n还没变为0,这时候要验证n的值,当n>0时候,p1指向的节点就是要删除的节点

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
 9     if(head==NULL)
10         return head;
11     struct ListNode *p1,*p2,*tmp;
12     p1=head;
13     p2=head;
14     while(n>0&&p2->next!=NULL){
15         p2=p2->next;
16         n--;
17     }
18     if(n>0){
19         tmp=p1;
20         head=p1->next;
21         free(tmp);
22     }
23     else
24     {
25     while(p2->next!=NULL){
26         p2=p2->next;
27         p1=p1->next;
28     }
29     tmp=p1->next;
30     if(tmp!=NULL){
31         p1->next=tmp->next;
32         free(tmp);
33     }
34     }
35     return head;
36 }

 

posted @ 2016-12-23 17:56  wilderness  阅读(151)  评论(0编辑  收藏  举报