码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-09-07 00:42:42      阅读:63      评论:0      收藏:0      [点我收藏+]

标签:else   move   位置   rom   src   链表   节点   from   head   

通过两次扫描实现。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;
    }
}

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

标签:else   move   位置   rom   src   链表   节点   from   head   

原文地址:https://www.cnblogs.com/WillamZ/p/11478806.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!