LeetCode----- 19.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個節點並返回它的頭部。

解題思路:本題要求是從一個單鏈表中刪除倒數第n個節點,並且返回新的鏈表。用個指針指向單鏈表,再計算單鏈表中節點的個數,然後節點的個數減去要刪除的倒數第n個數得到指針需要移動的次數。移動pos次後,將當前節點的next指向下一個節點的next。


代碼如下:

public class RemoveNthNodeFromEndofList {
    public static ListNode removeNthFromEnd(ListNode head, int n) {
    	if(head == null) {
    		return null;
    	}
    	int num = 0;
    	ListNode ret = new ListNode(0);
    	ret.next = head;
    	while(head != null) {
    		num++;
    		head = head.next;
    	}
    	ListNode currentNode = ret;
    	for(int i=0; i< num-n; i++) {
    		currentNode = currentNode.next;
    	}
    	currentNode.next = currentNode.next.next;
    	return ret.next;
    }
    
	public static void main(String[] args) {
		ListNode head = new ListNode(1);
		ListNode head1 = new ListNode(2);
		ListNode head2 = new ListNode(3);
		ListNode head3 = new ListNode(4);
		ListNode head4 = new ListNode(5);
		head.next = head1;
		head1.next = head2;
		head2.next = head3;
		head3.next = head4;
		head4.next = null;
		head = removeNthFromEnd(head,2);
		while(head != null) {
			if(head.next == null) {
				System.out.println(head.val);
			}else {
				System.out.print(head.val+"->");
			}
			head = head.next;
		}
	}    
}
class ListNode {
	int val;
	ListNode next;
	ListNode(int x) { 
		val = x;
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章