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

leetcode做题总结,题目Remove Nth Node From End of List 2012/01/27

2014-11-29 09:31 411 查看
删除链表倒数第N的节点,也没什么难度,用两个指针相隔N个节点,然后同时向后移动,一个到末尾另一个就是第N个节点。

/**
* 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) {
ListNode newhead = new ListNode(0);
ListNode start = new ListNode(0);
ListNode end = new ListNode(0);
newhead.next = head;
end=newhead;
start=newhead;

for(int i=0;i<n;i++){
if(end.next!=null){
end=end.next;
}else
return head;
}
while(end.next!=null){
end=end.next;
newhead=newhead.next;
}
newhead.next=newhead.next.next;
return start.next;
}
}


Update 2015/08/28: 上面的题目一上来直接创建三个节点我就呵呵了。。也不知道当时是怎么想的。下面来个正常的吧

/**
* Definition for ListNode.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int val) {
*         this.val = val;
*         this.next = null;
*     }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: The head of linked list.
*/
ListNode removeNthFromEnd(ListNode head, int n) {
// write your code here
if (n <= 0) {
return null;
}

ListNode start = new ListNode(0);
start.next = head;

ListNode p = start;
for (int i = 0; i < n; i++) {
if (head == null) {
return null;
}
head = head.next;
}
while (head != null) {
head = head.next;
p = p.next;
}
p.next = p.next.next;
return start.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: