Fork me on GitHub

LeetCode 19 Remove Nth Node From End of List (移除距离尾节点为n的节点)

 
Problem: 移除距离尾节点为n的节点. 
 
使用快慢指针,(由于是对链表进行操作,并且是距离尾节点距离为n,因此将快指针移动n个,慢指针移动到fast.next==null即可)
 
参考代码
package leetcode_50;

/***
 * 
 * @author pengfei_zheng
 *    移除距离尾节点为n的节点
 */
public class Solution19 {
    
    public class ListNode {
         int val;
         ListNode next;
         ListNode(int x) { val = x; }
     }
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head.next == null) {
            return null;
        }
        int counter = 1;
        ListNode start = new ListNode(0);
        start.next = head;//保存头指针
        ListNode fast = start;
        ListNode slow = start;
        while (fast.next != null) {//循环体
            fast = fast.next;//快指针移动
            if (counter <= n) {
                counter++;//计数器
            } else {
                slow = slow.next;//慢指针移动
            }
        }
        slow.next = slow.next.next;//移除
        return start.next;
    }
}

 

posted @ 2017-03-08 12:56  伊甸一点  阅读(173)  评论(0编辑  收藏  举报