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 }
?