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

Remove Nth Node From End of List

2015-12-11 01:02 477 查看
题目:

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.
首先我加了个头指针head1便于处理(这样就不用把只有一个节点,并且要求删除它的情况单独拿出来处理了),然后用两个指针p,q,先让一个指针p先走n步,然后p,q一起运动,直到p.next == null,然后删除q.next即可,具体代码如下:
/**
* 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 head1 = new ListNode(0);
head1.next = head;
ListNode p = head1,q = head1;
for(int i = 0;i < n;i++) {
p = p.next;
}
while(p.next != null) {
p = p.next;
q = q.next;
}
p = q.next;
q.next = q.next.next;
p = null;//提醒Java虚拟机它可以被回收了。。。
return head1.next;
}
}


PS:注意因为题目要求只遍历一遍,所以这样写,但这样写并不会比那种先遍历一遍获取链表长度,然后算出删除的节点是正数第几个,再遍历删除它效率高。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: