删除单链表中的倒数第n个节点(Java实现)

LeetCode题目链接(https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/submissions/)

ADT:
	public class ListNode {
      	int val;
     	ListNode next;
       	ListNode(int x) { val = x; }
    }


    //方法说明:声明两个指针,初始都指向头节点,当前指针移动了n步后,后指针开始移动,
    当后指针移动到尾节点,表示前指针所在的节点的下一个节点为要删除的节点。
    
    public ListNode removeNthFromEnd(ListNode head, int n) { 
        //声明两个指针
        ListNode front = head;
        ListNode later = head;
        //声明一个计数器,确定前指针移动的步数以启动后指针移动
        int count = 0;
        while(front.next!=null){
            front = front.next;
            if(count==n){
                later = later.next;   
            }else{
                count++;
            }
        }
        //如果count不等于n则表示later还未移动,front已经走到尾端,则表明删除的节点就是头节点。
        if(count!=n){
            head = head.next;
            return head;
        }
        //否则删除later后的一个节点
        later.next = later.next.next;
        return head;
    }

题目拓展:删除第n个节点

	public ListNode removeNthFromEnd(ListNode head, int n) {
	//声明两个指针,表示为当前所在节点以及前驱节点
    ListNode prev = head;
    ListNode cur = prev.next;
    int tmp = 2;
    //删除头节点单独处理
    if(n==1){
        return head.next;
    }
    while(cur!=null){
        if(tmp == n){
            prve.next = cur.next;
            return head;
        }
        cur = cur.next;
        prev= prev.next;
        tmp++;
    }
    return null;
}

猜你喜欢

转载自blog.csdn.net/weixin_43695091/article/details/88379435
今日推荐