Remove Nth Node From End of List

来源:互联网 发布:淘宝win10激活码木马 编辑:程序博客网 时间:2024/06/06 01:03

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+1步,因为要获得前面一个node,然后fast slow一起走,注意,fast!=null, fast = fast.next,最后指向的是最后一个node,而不是null。

自己写出来的代码,好开心!

/**  * 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) {         if(head == null ) return null;         int len = 0;         ListNode node = head;         while(node!=null){             node = node.next;             len++;         }         if(n == len) return head.next;         if(n > len) return head;         ListNode slow = head;         ListNode fast = head;         int step = n;         while(step > 0){             fast = fast.next;             step--;         }                  while(fast!= null && fast.next!=null){             slow = slow.next;             fast = fast.next;         }         slow.next = slow.next.next;         return head;     } }


0 0
原创粉丝点击