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


个人认为另外一种方法也没有什么太多优化,仅仅是为了满足题目要求。

可是这种方法联想到能够解决非常多链表相关问题。比方求两个链表相交结点也能够通过这样的类似这样的路程关系解决。

原文地址:https://www.cnblogs.com/tlnshuju/p/6900612.html