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

LeetCode_19---Remove Nth Node From End of List

2015-06-05 14:26 501 查看
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.
翻译:

Code:

/**
* @author MohnSnow
* @time 2015年6月5日 下午2:27:01
*
*/
public class LeetCode19 {

static class ListNode {
int val;
ListNode next;

ListNode(int x) {
val = x;
}

@Override
public String toString() {
if (this.next != null) {
return val + "---" + this.next.toString();
} else {
return val + "";
}
}
}
//304msA
public static ListNode removeNthFromEnd(ListNode head, int n) {
if(n == 0){
return head;
}
System.out.println("删除倒数第 " + n + " 个");
int i = 1;
ListNode iNode = head;
ListNode jNode = head;
while (iNode.next != null) {
iNode = iNode.next;
i++;
if (i > n + 1) {
jNode = jNode.next;
}
}
System.out.println("jNode是: "+jNode);
if (i >= n) {
if (jNode == head&&i==n) {
System.out.println("删除第一个:");
return head.next;//删除第一个
} else {
System.out.println("删除倒数第N个:");
jNode.next = jNode.next.next;
return head;
}
} else {
System.out.println("N太大,不做删除:");
return head;//n大于长度,不做删除
}
}

public static void main(String[] args) {
ListNode a = new ListNode(1);
ListNode b = new ListNode(2);
ListNode c = new ListNode(3);
ListNode d = new ListNode(4);
ListNode e = new ListNode(5);
a.next = b;
b.next = c;
c.next = d;
d.next = e;
e.next = null;
System.out.println(removeNthFromEnd(a, 0));
}

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