leetcode 19: Remove Nth Node From End of List

来源:互联网 发布:java把html写入pdf 编辑:程序博客网 时间:2024/06/03 01:56

问题描述:

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.

思路:

题目看来挺简单,主要就是设置一个前行节点一个后行节点,同步控制两节点距离一直到链表末端。但是实践完成代码的思路上还是有一点点技巧和注意的。
这里我用了一个链表附加头节点,这样在删除头结点问题上可以很方便解决;然后注意要得到的节点应该是所要求删除节点的前一个节点;还有就是最后返回链表时,要返回更新后的head节点,因为head可能有改变。

代码:

/** * 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* prehead = new ListNode(-1);        prehead->next = head;        ListNode* bias = prehead;        ListNode* targetpre = prehead;        //bias move forward n steps        for(int i = 0; i < n; i++)          {            if(bias == NULL) return head;            bias = bias->next;           }        //bias point to the end, at the same time, target point to the previous node of the nth from the end.        while(bias->next != NULL)        {            bias = bias->next;            targetpre = targetpre->next;        }        ListNode* temp = targetpre->next;        targetpre->next = temp->next;        head = prehead->next;   //update the new head        delete temp;        delete prehead;        return head;    }};
0 0
原创粉丝点击