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

Remove Nth Node From End of List

2013-10-16 08:05 337 查看
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.

也可以用双指针(fast pointer) 来做,但是要注意 n = len的情况。

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
ListNode per = head;
ListNode cur = head;
ListNode before = head;
int len = 0;
while(per != null){
per = per.next;
len ++;
}
int num = len - n;
if(num == 0)return head.next;
else{
per = head;
for(int i = 0; i < num; i ++){
cur = per;
per = per.next;
}
cur.next = per.next;
return head;
}
}
}


第二遍:

public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
ListNode header = new ListNode(-1);
header.next = head;
ListNode cur = header;
ListNode per = header;
ListNode fast = header;
for(int i = 0; i < n; i ++){
fast = fast.next;
}
while(fast != null){
per = cur;
fast = fast.next;
cur = cur.next;
}
per.next = cur.next;
return header.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: