19. Remove Nth Node From End of List

来源:互联网 发布:linux启动ftp服务 编辑:程序博客网 时间:2024/06/05 16:15

这道题,我当时就觉得很有意思,就是加尾巴

原来是返回最后一个元素很容易,就是看.next==null?  那么倒数第二个就是.next.next==null? 现在是倒数第N个你怎么搞呢?其实就是说,要找到倒数第N个节点,那么最后,他会带有一个(N-1) 长度的尾巴,那么在一开始就把这个尾巴找到,然后就是一个window在整体移动,不是单个node在移动了,怎么实现?根据尾巴节点来实现。。

题目的意思是移除,那么就还要维护一个前继节点,找到目标节点后,就不同的删除方法即可


/** * 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) {        ListNode gun=head;        for(int i=1; i<=n;i++){            gun=gun.next;        }                ListNode current=head;        ListNode prev= current;        while(gun!=null){            gun=gun.next;            prev=current;            current=current.next;        }                if(current==head) head=head.next;        else prev.next=current.next;        return head;    }}

今天写的,稍微不同,就是定位的是最后一个end的节点,而以上的代码定位的是:end.next

/** * 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) {        ListNode end=head;        for(int i=1; i<n; i++){            end=end.next;        }                ListNode curr=head;        ListNode prev=curr;        while(end.next!=null){            prev=curr;            curr=curr.next;            end=end.next; // always for while loop        }                if(curr==head) return head.next; // in case curr did not move, which means that there is n node in total        prev.next=curr.next;        return head;    }}



0 0
原创粉丝点击