数据结构每日学习 Day13 删除链表倒数第N个节点

题目:

在这里插入图片描述
AC:

package 链表;


import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class 删除倒数第几个节点 {
      public class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }



    public ListNode removeNthFromEnd(ListNode head, int n) {
            //ListNode dummy= new ListNode(0,head);
            ListNode first=head;
            ListNode second=head;

          for (int i = 0; i <n ; i++) {
                first=first.next;

          }
          if(first==null){
                head=head.next;
                return head;
          }
          while (first.next!=null){
                first=first.next;
                second=second.next;
          }
          second.next=second.next.next;

          return head;





    }
      public ListNode removeNthFromEnd2(ListNode head, int n) {
            ListNode dummy= new ListNode(0,head);
            ListNode first=head;
            ListNode second=dummy;

            for (int i = 0; i <n ; i++) {
                  first=first.next;

            }
//            if(first==null){
//                  head=head.next;
//                  return head;
//            }
            while (first!=null){
                  first=first.next;
                  second=second.next;
            }
            second.next=second.next.next;
            return head;
      }

      public ListNode removeNthFromEnd3(ListNode head, int n) {
            ListNode dummy= new ListNode(0,head);
            Deque<ListNode> stack=new LinkedList<>();

            ListNode cur=dummy;
            while (cur!=null){
                  stack.push(cur);
                  cur=cur.next;
            }

            for (int i = 0; i <n ; i++) {
                  stack.pop();

            }

            ListNode node=stack.peek();
            node.next=node.next.next;
            return dummy.next;
      }



}

PS:

一共是3种做法
1 其中如果没有娅节点定义的话 快慢指针都在head节点开始,那么有个极端问题就是如果删除的是头节点 有一个判空问题
因为这里的first不能为空
在这里插入图片描述
2 定义娅节点 很好用 慢指针一开始在娅节点 不然如果一开始都在头节点 那么最后快节点到达null,慢节点到达要删除的,而用娅节点后,则刚刚好下一个就是要删除的
3 栈

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值