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.
删除倒数第n个节点,主要有两种做法
法一:先遍历得到链表的长度length,倒数第n个就是正数第length-n+1个(如1 2 3,倒数第三个节点就是3-3+1=1,即第一个节点)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* newlist= new ListNode(0); newlist->next = head; //带头节点的链表 int length = 0; ListNode* first = head; while(first != NULL){ //得到链表长度 length++; first = first->next; } if(n > length) return NULL; int n1 = length + 1 - n;//倒数第n个是在正数第n1个节点 first = newlist; while(n1 - 1 > 0){ //找到目标节点的前一个位置,便于删除目标节点 n1--; first = first->next; } first->next = first->next->next; //删除目标节点 return newlist->next; //返回不带头节点的链表 } };
法二:利用两个指针,快指针先走,找到第n个节点,再启动慢指针。
此时快慢指针相距n,让两个指针一起走,快指针走到尾节点时,慢指针刚好到倒数第n个节点。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *removeNthFromEnd(ListNode *head, int n) { if (!head) return nullptr; ListNode new_head(-1); new_head.next = head; ListNode *slow = &new_head, *fast = &new_head; for (int i = 0; i < n; i++) //快指针先走到第n个节点 fast = fast->next; while (fast->next) //快慢指针一起走 { fast = fast->next; slow = slow->next; } ListNode *to_do_deleted = slow->next; //这两行负责删除操作 slow->next = slow->next->next; delete to_do_deleted; return new_head.next; } };
时间: 2024-11-09 06:07:05