码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Nth Node From End of List

时间:2014-08-31 10:31:51      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:remove nth node from   leetcode   链表删除   

地址: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;
    }
}


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

Remove Nth Node From End of List

标签:remove nth node from   leetcode   链表删除   

原文地址:http://blog.csdn.net/huruzun/article/details/38958335

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!