LeetCode OJ算法题(十九):Remove Nth Node From End of List

来源:互联网 发布:上海交通大学知乎 编辑:程序博客网 时间:2024/06/05 00:39

题目:

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.

解法:

题目很简单,就是链表的元素删除,思路有两种:

第一种,先遍历一边链表,得到链表的长度L,然后由L-n+1找到要删除的元素,这种时间复杂度为O(2n)

第二种,只遍历一遍链表,但遍历的同时,维持一个大小为n+1的数组,用来实时保存最近遍历到的n+1个元素,当遍历完成时,只需删除array[n]指向的元素即可。

当然需要注意,若array没有被填满,即n>=L时,需要单独处理下。

public class No19_RemoveNthNodeFromEndOfList {public static class ListNode {int val;ListNode next;ListNode(int x) {val = x;next = null;}}public static void main(String[] args){ListNode n1 = new ListNode(1);ListNode n2 = new ListNode(2);ListNode n3 = new ListNode(3);ListNode n4 = new ListNode(4);ListNode n5 = new ListNode(5);n1.next = n2;n2.next = n3;n3.next = n4;n4.next = n5;ListNode head = n1;//ListNode x = removeNthFromEnd_1(head, 2);ListNode x = removeNthFromEnd_2(head, 5);while(x!=null){System.out.println(x.val);x = x.next;}}public static ListNode removeNthFromEnd_1(ListNode head, int n) {int l = 0;ListNode p = head;while(p != null){p=p.next;l++;}if(n > l) return head;if(n == l) return head.next;int i = 1;p = head;while(i<l-n){p = p.next;i++;}ListNode tmp = p.next.next;p.next.next = null;p.next = tmp;        return head;    }public static ListNode removeNthFromEnd_2(ListNode head, int n) {ListNode[] nodeArr = new ListNode[n+1];ListNode p = head;while(p != null){for(int i=n;i>0;i--){nodeArr[i] = nodeArr[i-1];}nodeArr[0] = p;p = p.next;}if(nodeArr[n] == null) return head.next;ListNode tmp = nodeArr[n].next.next;nodeArr[n].next.next = null;nodeArr[n].next = tmp;        return head;    }}


0 0