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

LeetCode 19 Remove Nth Node From End of List (移除距离尾节点为n的节点)

2017-03-08 12:56 344 查看
题目链接 https://leetcode.com/problems/remove-nth-node-from-end-of-list/?tab=Description

Problem: 移除距离尾节点为n的节点.

使用快慢指针,(由于是对链表进行操作,并且是距离尾节点距离为n,因此将快指针移动n个,慢指针移动到fast.next==null即可)

参考代码

package leetcode_50;

/***
*
* @author pengfei_zheng
*    移除距离尾节点为n的节点
*/
public class Solution19 {

public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head.next == null) {
return null;
}
int counter = 1;
ListNode start = new ListNode(0);
start.next = head;//保存头指针
ListNode fast = start;
ListNode slow = start;
while (fast.next != null) {//循环体
fast = fast.next;//快指针移动
if (counter <= n) {
counter++;//计数器
} else {
slow = slow.next;//慢指针移动
}
}
slow.next = slow.next.next;//移除
return start.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐