刪除鏈表的倒數第N個節點
給定一個鏈表,刪除鏈表的倒數第 n 個節點,並且返回鏈表的頭結點。
說明:給定的n保證是有效的。
給定一個鏈表: 1->2->3->4->5, 和 n = 2. 當刪除了倒數第二個節點后,鏈表變為 1->2->3->5.
分析:首先遍歷鏈表中一共有多少個元素,然后查找倒數第n個元素,並把它刪除。
下邊是代碼實現:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * struct ListNode *next; 6 * }; 7 */ 8 9 10 struct ListNode* removeNthFromEnd(struct ListNode* head, int n){ 11 struct ListNode* list = head; 12 int i=0; 13 while(list!=NULL){ 14 i++; 15 list=list->next; 16 } 17 list = head; 18 if(n==i){ 19 head=head->next; 20 free(list); 21 return head; 22 } 23 int index=1; 24 while(index!=i-n){ 25 list=list->next; 26 index++; 27 } 28 struct ListNode *body = list->next; 29 list->next=list->next->next; 30 free(body); 31 return head; 32 }