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

leetcode19:Remove Nth Node From End of List

2016-12-15 09:04 405 查看

Remove Nth Node From End of List

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.

其实挺简单的一道题,不过还是没想出来。最后看别人的思路,恍然大悟。。。。

线性思路很巧妙啊,保存两个相差n的指针,当后一个指针指向最后一个元素时,前一个指针就指向要删除元素的前一个元素了。

package leetcode;

public class leet19 {

private static class ListNode{
int val;
ListNode next;
ListNode(int x){ val = x; }
ListNode(){ }
}
public static void main(String[] args) {//main方法

ListNode head = new leet19.ListNode();
ListNode n1 = new leet19.ListNode(1);
ListNode n2 = new leet19.ListNode(2);
ListNode n3 = new leet19.ListNode(3);
ListNode n4 = new leet19.ListNode(4);
ListNode n5 = new leet19.ListNode(5);
head.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
n5.next = null;

leet19 leet = new leet19();
ListNode node = leet.removeNthFromEnd2(head, 1);
System.out.println(node.val);
System.out.println("-------------------------------");
ListNode n = head;
while(n.next != null){
System.out.println(n.next.val);
n = n.next;
}
}

//自己的思路,循环两遍,没有加头结点
public ListNode removeNthFromEnd(ListNode head,int n){

ListNode Node = head;//要找的节点
ListNode returnNode;
int totall = 1;//记录总节点数

while(true){//循环一遍链表,确定链表长度

if(Node.next == null){
break;
}
totall++;
Node = Node.next;
}

if(n > totall || n <= 0){
System.out.println("n大于链表长度或者为负为0");
return null;
}
Node = head;//Node节点重新指向第一个节点
int nthEnd = totall - n;//确定要删除的节点的前一个节点的位置
int count = 1;
while(count < nthEnd){//循环的找出要删除的节点的前一个节点
count++;
Node = Node.next;
}
returnNode = Node.next;//要删除并返回的节点
if(n == 1){//如果要删除的是最后一个节点则,倒数第二个节点的next指针指向null
Node.next = null;
}else{
Node.next = returnNode.next;//删除节点
}
return returnNode;
}

//线性方法,看了别人的思路写的,这次加上了加了头结点,深刻体会到头结点的方便性
public ListNode removeNthFromEnd2(ListNode head,int n){

ListNode p = head;
ListNode q = head;
ListNode result;
int count = 0;
while(count < n){
count++;
p = p.next;
}
while(p != null && p.next != null){

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