19. Remove Nth Node From End of List

来源:互联网 发布:win7 传奇3 数据库 编辑:程序博客网 时间:2024/06/04 23:35

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个位置,这样快指针变成null的时候慢指针就指到了要删掉的位置,这个新方法其实比较好。

这里用的方法是把所有节点存起来orz……当年怎么想到这么有创意的方法……然后把上一个指到后一个……

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode removeNthFromEnd(ListNode head, int n) {        List<ListNode> node = new ArrayList<ListNode> ();        int count=0;        for(ListNode a=head;a!=null;a=a.next){            count++;            node.add(a);        }     //   if(n==1&&count>=2)node.get(count-2).next=null;        if(n==count)head=head.next;        if(1<=n&&n<count)node.get(count-n-1).next=node.get(count-n).next;        return head;    }}

0 0
原创粉丝点击