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

leetcode-19. Remove Nth Node From End of List(删除链表倒数第N个节点)

2017-05-23 19:53 771 查看
https://leetcode.com/problems/remove-nth-node-from-end-of-list/#/description

假设有一个结构体代表每个链表中的节点

struct ListNode {

* int val;

* ListNode *next;

* ListNode(int x) : val(x), next(NULL) {}

* };

问题描述:

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个位置,然后两个指针一起移动。当第二个指针移动到最后,则第一个指针,正好移动到倒数第n个位置。

代码如下:

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;//节点的值
*     ListNode next;//下一个指针
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {

ListNode start=new ListNode(0);//创建一个节点,含参构造方法。

ListNode s=start,e=start;

s.next=head;

for(int i=0;i<=n;i++)
{
e=e.next;
}

while(e!=null)
{
s=s.next;
e=e.next;
}

s.next=s.next.next;

return start.next;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode
相关文章推荐