链表-----删除倒数第k个节点

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 17:02   1183   0

注意点:

  • 删除头节点的处理
  • 在双链表中删除最后一个节点指针悬空情况

代码

public static class Node{
  public int value;
  public Node next;
  
  public Node(int value) {
   this.value = value;
  }
 }
 public static class DoubleNode{
  public int value;
  public  DoubleNode next;
  public  DoubleNode last;
  
  public  DoubleNode(int value) {
   this.value = value;
  }
 }
 
 public static Node removeLastkth(Node head,int k) {
  if(head == null || k < 1) return null;
  Node cur = head;
  int size = 0;
  while(cur != null) {
   cur = cur.next;
   size++;
  }
  
  if(k == size) {
   head = head.next;
   return head;
  }
  cur = head;
  int count = size - k;//删除节点的前一个节点
  while(--count != 0) {
   cur = cur.next;
  }
  cur.next = cur.next.next;
  
  return head;
  
 }
 
 public static Node removeLastkth2(Node head,int k) {
  if(head == null || k < 1) return null;
  Node cur = head;
  
  while(cur != null) {
   k--;
   cur = cur.next;
  }
  
  if(k == 0) {
   head = head.next;
   return head;
  }
  cur = head;
  while(++k != 0) {
   cur = cur.next;
  }
  cur.next = cur.next.next;
  
  return head;
  
 }
 
 
 public static DoubleNode removeDoubleLastkth(DoubleNode head,int k) {
  if(head == null || k < 1) return null;
  DoubleNode cur = head;
  int size = 0;
  while(cur != null) {
   cur = cur.next;
   size++;
  }
  
  if(k == size) {
   head = head.next;
   head.last = null;
   return head;
  }
  cur = head;
  int count = size - k;//删除节点的前一个节点
  while(--count != 0) {
   cur = cur.next;
  }
  cur.next = cur.next.next;
  //注意指针悬空情况:删除最后一节点的时候  cur.next == null 
  if(cur.next != null) {
   cur.next.last = cur;
  }
  
  return head; 
 }
 
 public static DoubleNode removeDoubleLastkth2(DoubleNode head,int k) {
  if(head == null || k < 1) return null;
  DoubleNode cur = head;
  while(cur != null) {
   k--;
   cur = cur.next; 
  }
  
  if(k == 0) {
   head = head.next;
   head.last = null;
   return head;
  }
  cur = head;
  while(++k != 0) {
   cur = cur.next;
  }
  cur.next = cur.next.next;
  //注意指针悬空情况:删除最后一节点的时候  cur.next == null 
  if(cur.next != null) {
   cur.next.last = cur;
  }
  
  return head; 
 }

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP