您的位置:首页 > Web前端 > Node.js

leetcode: (19) Remove Nth Node From End of List

2015-08-24 20:17 537 查看
【Question】

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.

方法一:题目要求删除倒数的第n个节点
首先,必须就算出一共有多少节点,才能知道要删除的节点的位置,通过一次遍历,计算出总的节点数;

然后,再一次遍历到倒数第n个节点的前一个节点,然后进行删除操作;

其中要注意的是

1)n=总的节点数 时 ,此时要删除的节点为首指针,只需将head=head->next;即可

class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *cur,*p,*temp,*pre;
p=head;
cur=head;
int count=0;
while(p!=NULL)
{
p=p->next;
count++;
}
temp=(ListNode *)malloc(sizeof(ListNode));
if (count==n) {head=head->next;;return head;}
else
{
for(int i=0;i<count-n;i++)
{
pre=cur;
cur=cur->next;
}
temp=pre->next;
pre->next=temp->next;
free(temp);
}
return head;
}
};

Runtime: 4
ms

方法二:由于倒数第n个点到头结点的距离=第n个点的距离到尾节点的距离,所以不必进行第一次遍历得出总的节点数.

public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode curr = head;
ListNode pre = head;
for(int i = 0;i < n;i++)
curr = curr.next;
if(curr == null)
return head.next;
while(curr.next != null)
{
curr = curr.next;
pre = pre.next;
}
pre.next = pre.next.next;
return head;
}
}Runtime: 272
ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithms leetcode 链表