leetcode19.删除链表的倒数第N个节点

通过两次扫描实现。ToDo:用一趟扫描实现

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        int length = 0;
        int pos;
        int count = 0;
        if(head == null){
            return null;
        }
        ListNode curNode = head;
        //获取链表长度
        while(curNode != null){
            length++;
            curNode = curNode.next;
        }
        //正序位置,从0开始计数
        pos = length - n;
        
        if(pos == 0){
            return head.next;
        }
        
        curNode = head;
        while(true){
            count++;
            if(count != pos){
                curNode = curNode.next;
            }else{
                curNode.next = curNode.next.next;
                break;
            }
        }
        return head;
    }
}
posted @ 2019-09-06 23:21  WillamZ  阅读(100)  评论(0)    收藏  举报