LeetCode-19. Remove Nth Node From End of List

一、问题描述

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.

二、解题思路

思路一:遍历两遍链表,第一遍计算链表的总长度,第二遍定位需要移除的链表元素。

思路二:遍历一遍链表,定义两个变量first和second,分别指向链表不同的元素,并且满足first-second=n,然后first和second不断自增,当first指向的元素的下一个是null是,second就指向了目标元素的上一个,然后执行移除操作。

三、代码

思路一:

/**
 * 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) {
        ListNode result=new ListNode(0);//如果result直接指向head,需要考虑当链表的长度等于n时,即移除第一个链表元素时这种情况。
        result.next=head;
        if(head==null || n<=0)
            return head;
        int count=0;
        while(head!=null){
            head=head.next;
            count++;
        }
        int i=0;
        head=result;
        while(true){
            if(i==count-n){
                head.next=head.next.next;
                break;
            }
            head=head.next;
            i++;
            
        }
        return result.next;
    }
}
思路二:
/**
 * 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) {
        ListNode result=new ListNode(0);
        result.next=head;
        if(head==null || n<=0)
            return head;
        ListNode first=result;
        ListNode second=result;
        for(int i=0;i<n;i++){
            first=first.next;
        }
        while(first.next!=null){//如果这里判断的是first!=null,则前面first需要移动n+1
            first=first.next;
            second=second.next;
        }
        second.next=second.next.next;
        return result.next;
    }
}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值