题目描述
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.
解题思路:参照找倒数第k个结点那个题
1)两个指针p1 p2 p2先走k-1,然后两个指针一起走,p2走到最后,p1即为倒数第k个结点pre为倒数第k+1个结点
2)从链表中删除第k个节点
本题应注意边界条件的判断:
1)链表为空
2)要删除的正好是第一个结点的情况
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 if(head == NULL) 13 return NULL; 14 ListNode *pPre = NULL; 15 ListNode *p1 = head; 16 ListNode *p2 = head; 17 for(int i=0;i<n-1;i++) 18 { 19 p2 = p2->next; 20 } 21 while(p2->next != NULL) 22 { 23 pPre = p1; 24 p1 = p1->next; 25 p2 = p2->next; 26 } 27 if (pPre == NULL)//正好要删除的就是第一个结点 28 { 29 head = p1->next; 30 delete p1; 31 } 32 else 33 { 34 pPre->next = p1->next; 35 delete p1; 36 } 37 38 return head; 39 } 40 };
时间: 2024-12-29 04:00:04