读书人

leetcode:Remove Nth Node From End

发布时间: 2013-10-22 16:17:03 作者: rapoo

leetcode:Remove Nth Node From End of List(删除链表倒数第n个节点)【面试算法题】

题目:

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个节点,不改变链表其他节点结构,返回链表头指针。



由于链表是单向的,不能倒着搜索,因此设置两个指针,他们相隔n个节点的距离,同布移动。

当前面的指针到达链表结尾的时候,后面一个指针离结尾的距离正好是n,再删除要求的节点就ok了。

要注意的我觉得应该有两点:

第一如果链表不到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) {        ListNode *left,*right,*Head;        right=head;        for(int i=0;i<n;++i)        {            if(!right)return head;            right=right->next;        }        Head=left=new ListNode(-1);        Head->next=head;        while(right)        {            right=right->next;            left=left->next;        }        ListNode *t1=left->next,*t2;        if(t1)left->next=left->next->next;        delete(t1);        t2=Head->next;        delete(Head);        return t2;    }};// blog.csdn.net/havenoidea

题解目录

读书人网 >其他相关

热点推荐