package zz; import java.util.Stack; import zz.LinkedListSummary.Node; /** * 参考博客:http://blog.csdn.net/lavor_zl/article/details/42803431 * @author zz * 关于java中链表的操作 * 0. 删除带头结点的单链表的节点p,p不是尾节点,并且要求时间复杂度为O(1) * 1. 删除带头结点的单链表的节点p,p可能为尾节点,也可能是任意其他节点 */ public class LinkedListSummary2 { public static class Node { int data; Node next; public Node(int value) { data = value; } } //向链表中插入新节点 public static Node addNode(Node head, int data) { Node newNode = new Node(data); if(head == null) { head = newNode; } Node temp = head; while(temp.next != null) { temp = temp.next; } temp.next = newNode; return newNode; } //顺序打印链表数据 public static void print(Node head) { if(head == null) { System.out.println("链表为空"); return; } else { Node temp = head; while(temp != null) { System.out.print(temp.data + " "); temp = temp.next; } } } //删除带头结点的单链表的节点p,p不是尾节点,并且要求时间复杂度为O(1) public static void deleteNode(Node p) { if(p == null || p.next == null) return; Node q = p.next; p.data = q.data; p.next = q.next; } //删除带头结点的单链表的节点p,p可能为尾节点,也可能是任意其他节点 public static void deleteNode(Node head, Node p) { if(head == null || p == null) return; Node temp = null; if(p.next != null) { //p不是尾节点 Node n = p.next; p.data = n.data; p.next = n.next; } else { //p是尾节点 Node node = head; while(node.next != null) { temp = node; node = node.next; } temp.next = null; } } public static void main(String[] args) { Node head = new Node(0); Node h1 = addNode(head, 1); Node h2 = addNode(head, 2); Node h3 = addNode(head, 3); Node h4 = addNode(head, 4); Node h5 = addNode(head, 5); System.out.println("顺序打印单链表:"); print(head); System.out.println(); System.out.println("删除链表头结点:"); deleteNode(head, h5); print(head); System.out.println(); } }