目标:
给出一个链表的head,和n,删除该链表倒数第n个节点,并返回head。尽量使用一个循环实现。
思路:
用一个指针index来遍历的链表,同时用一个整形count记录搜索节点的迭代次数,直到与题目输入的n相等。
这时候,用一个指针before_remove来记录应该被删的节点的前一个节点。
同时,这时候before_remove与index同时开始迭代。直到index为链表最后一个节点。
这时候,如果count与n相等,即证明before_remove记录的是正确的应该被删的节点的前一个节点。
如果count与n不相等,又因为题目说n的输入是绝对正确的,所以只能这时应该删除的节点是head,所以导致没有应该被删节点的前一个节点。
接下来就是节点的删除工作,分别对应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 ListNode* before_remove = head; 13 ListNode* index = head; 14 int count = 0; 15 /* find the node that before the node which should be removed */ 16 while (index -> next != NULL) { 17 index = index -> next; 18 if (count == n) 19 before_remove = before_remove -> next; 20 else 21 count++; 22 } 23 /* make the pointer correct and remove the node */ 24 ListNode* should_remove; 25 // normal situation 26 if (count == n) { 27 should_remove = before_remove -> next; 28 before_remove -> next = should_remove -> next; 29 } 30 // the head node should be removed 31 else { 32 should_remove = head; 33 head = head -> next; 34 } 35 delete should_remove; 36 return head; 37 } 38 };