leetcode19:Remove Nth Node From End of List

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;
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值