首页 > 其他 > 详细

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

时间:2019-09-07 09:17:54      阅读:90      评论:0      收藏:0      [点我收藏+]

通过两次扫描实现。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个节点

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!