Java 单链表的删除操作

    技术2022-07-21  86

    测试代码

    package com.zhangyu; public class LinkedListTest { /** * 定义节点的结构 */ static class Node { int data; Node next; public Node(int data) { this.data = data; } @Override public String toString() { if (this.next == null) { return String.valueOf(this.data); } return this.data + "->" + this.next.toString(); } } /** * @param head 链表头结点 * @param position 待删除节点的位置 * @return 返回删除后的链表 */ public static Node removeNode(Node head, int position) { //头结点为空,或者删除位置不对,直接返回 if (head == null || position < 0) { return head; } //如果删除的是头结点 if (position == 0) { head = head.next; return head; } // //遍历,找到这个节点 int curPosition = 1; Node preNode = head; Node curNode = head.next; while (curNode != null) { //当前的位置,等于要找的位置 if (curPosition == position) { preNode.next = curNode.next; break; } curPosition++; preNode = preNode.next; curNode = curNode.next; } return head; } /** * @param head 链表头结点 * @param removeNode 待删除的节点 * @return 删除后的链表 */ public static Node removeNode(Node head, Node removeNode) { //空返回 if (head == null || removeNode == null) { return head; } //待删除的节点是头结点 if (removeNode == head) { head = head.next; return head; } //如果是尾节点 if (removeNode.next == null) { //找到尾节点的前一个节点 Node curNode = head; while (curNode.next != removeNode) { curNode = curNode.next; } curNode.next = null; return head; } //中间节点 Node tmp = removeNode.next; removeNode.data = tmp.data; removeNode.next = tmp.next; return head; } /** * 得到尾节点 * * @param head 头节点 * @return 返回尾节点 */ public static Node getTailNode(Node head) { while (head.next != null) { head = head.next; } return head; } public static void main(String[] args) { Node head = createNewLinkedList(); System.out.println("新建一个链表:\n" + head); System.out.println("删除尾节点:\n" + removeNode(head, 9)); System.out.println("删除中间节点:\n" + removeNode(head, 2)); System.out.println("删除头结点:\n" + removeNode(head, 0)); System.out.println("---------------------------"); head = createNewLinkedList(); System.out.println("新建一个链表:\n" + head); System.out.println("删除尾节点:\n" + removeNode(head, getTailNode(head))); System.out.println("删除中间节点:\n" + removeNode(head, head.next.next)); System.out.println("删除头结点:\n" + removeNode(head, head)); } /** * 创建一个新的链表 * * @return 新链表 */ private static Node createNewLinkedList() { Node head = new Node(0); Node curNode = head; for (int i = 1; i < 10; i++) { curNode.next = new Node(i); curNode = curNode.next; } curNode.next = null; return head; } }

    测试结果

    新建一个链表: 0->1->2->3->4->5->6->7->8->9 删除尾节点: 0->1->2->3->4->5->6->7->8 删除中间节点: 0->1->3->4->5->6->7->8 删除头结点: 1->3->4->5->6->7->8 --------------------------- 新建一个链表: 0->1->2->3->4->5->6->7->8->9 删除尾节点: 0->1->2->3->4->5->6->7->8 删除中间节点: 0->1->3->4->5->6->7->8 删除头结点: 1->3->4->5->6->7->8
    Processed: 0.009, SQL: 9