本文共 1780 字,大约阅读时间需要 5 分钟。
在编程中,链表的操作是一个非常基础但重要的技能。以下,我们将分别实现两个函数:一个用于删除单链表中倒数第K个节点,另一个用于删除双链表中倒数第K个节点。
public static Node removeLastKthNode(Node head, int lastKth) { if (head == null || lastKth < 1) { return head; } Node cur = head; // 第一遍遍历,计算总长度 while (cur != null) { lastKth--; cur = cur.next; } // 如果lastKth大于链表长度,直接返回头节点 if (lastKth > 0) { return head; } // 如果lastKth为0,删除最后一个节点 if (lastKth == 0) { return head.next; } // 一般情况,删除倒数第K个节点 cur = head; while (++lastKth != 0) { cur = cur.next; } cur.next = cur.next.next; return head;} public static DoubleNode removeLastKthNode(DoubleNode head, int lastKth) { if (head == null || lastKth < 1) { return head; } DoubleNode cur = head; // 第一遍遍历,计算总长度 while (cur != null) { lastKth--; cur = cur.next; } // 如果lastKth大于链表长度,直接返回头节点 if (lastKth == 0) { head = head.next; head.last = null; return head; } // 如果lastKth大于链表长度,直接返回头节点 if (lastKth > 0) { return head; } // 一般情况,删除倒数第K个节点 cur = head; while (++lastKth != 0) { cur = cur.next; } DoubleNode nextNode = cur.next; cur.next = nextNode; if (nextNode != null) { nextNode.last = cur; } return head;} 这些函数通过两次遍历链表,分别实现了删除单链表和双链表中倒数第K个节点的功能。需要注意的是,在双链表中,删除节点时需要同时处理前后节点的指针,确保链表的完整性。
转载地址:http://xuczz.baihongyu.com/