Remove Nth Node From End of List

地址:https://oj.leetcode.com/problems/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 值的合法性。最简单办法就是先遍历求得链表节点数目,然后删除指定结点,但是这样需要两次遍历链表。

public class Solution {
       public ListNode removeNthFromEnd(ListNode head, int n) {
    	if(head == null){
    		return null;
    	}
    	ListNode countList = head;
    	int ListCount = 0;
    	while(countList!=null){
    		ListCount++;
    		countList = countList.next;
    	}
    	if(ListCount-n==0){
    		return head.next;
    	}
    	ListNode ans = head;
    	int count = 0;
    	ListNode pre = null;
    	ListNode cur = null;
        while(head.next!=null){
        	count++;
        	pre = head;
        	cur = head.next;
        	if(count == ListCount-n){
        		pre.next = cur.next;
        		break;
        	}
        	head = head.next;
        }
        return ans;
    }
}


有个方法可以只需要进行一次链表遍历,参见:http://blog.csdn.net/huruzun/article/details/22047381

public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n){
    	ListNode pre = null;
    	ListNode ahead = head;
    	ListNode behind = head;
    	// ahead 节点先走n-1 步,behind 和ahead 一起走,当ahead到达最后一个节点,behind为需要删除元素
    	for(int i=0;i<n-1;i++){
    		if(ahead.next!=null){
    			ahead = ahead.next;
    		}else {
				return null;
			}
    	}
    	while(ahead.next!=null){
    		pre = behind;
    		behind = behind.next;
    		ahead = ahead.next;
    	}
    	// 如果删除的是头结点
    	if(pre == null){
    		return behind.next;
    	}else {
			pre.next = behind.next;
		}
    	return head;
    }
}


个人觉得第二种方法也没有什么太多优化,只是为了满足题目要求。但是这个方法联想到可以解决很多链表相关问题,比如求两个链表相交结点也可以通过这种类似这种路程关系解决。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值