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

leetcode - Remove Nth Node From End of List

2014-06-30 17:10 197 查看
题目:Remove Nth Node From End of List

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.

个人思路:

1、设置两个指针,一个快,一个慢,根据给定的n,让快指针先走n步,之后再同时走,直到快指针走到末节点,此时慢指针走到要删除节点的父节点

2、注意一下边界条件即可,链表为空、删除头节点等情况

代码:

#include <stddef.h>

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 NULL;
}

ListNode *slow = head;
ListNode *fast = head;

//快指针先走n步
for (int i = 0; i < n; ++i)
{
fast = fast->next;
}
//快指针为空,表明要删除的节点为头节点
if (!fast)
{
head = head->next;
delete slow;
slow = NULL;

return head;
}
//快指针走到最后一个节点时,慢指针走到要删除节点的前一个节点
while (fast->next)
{
slow = slow->next;
fast = fast->next;
}
//删除节点
ListNode *deleted = slow->next;
slow->next = deleted->next;
delete deleted;
deleted = NULL;

return head;
}
};

int main()
{
return 0;
}


View Code

网上的文章大部分都是这个思路
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: