class Node { int data; Node next; Node(){ next = null; } Node(int data) { this.data = data; next = null; } } class List { Node head = new Node(); List(int n){ Random rand = new Random(90); for (int i = 0; i < n; i++) { insert(rand.nextInt() % 100); } } public void insert(int data) { Node node = new Node(data); Node tmp; tmp = head; while (tmp.next != null) { if (data > tmp.next.data) break; tmp = tmp.next; } node.next = tmp.next; tmp.next = node; } public void delete(int data) { Node tmp; tmp = head; while (tmp.next != null) { if (data == tmp.next.data) { tmp.next = tmp.next.next; return; } tmp = tmp.next; } } public void reverse1() { Node pre, cur, last; pre = null; cur = head.next; while (cur != null) { last = cur.next; cur.next = pre; pre = cur; cur = last; } head.next = pre; } public void reverse2() { Node cur, last; cur = head.next; if (cur == null || cur.next == null) return; while (cur.next.next != null) cur = cur.next; last = cur.next; cur.next = null; reverse2(); last.next = cur; head.next = last; } public void reverse3() { Node cur, last; cur = head.next; if (cur == null || cur.next == null) return; last = cur.next; head.next = last; reverse3(); last.next = cur; cur.next = null; } public void show() { Node tmp; tmp = head.next; while (tmp != null) { System.out.print(tmp.data + " "); tmp = tmp.next; } System.out.println(); } } public class LinkList { public static void main(String[] args) { List list = new List(10); list.insert(10); list.show(); list.delete(5); list.reverse1(); list.show(); } }
java中链表的头结点_有头结点的单链表(java实现)
最新推荐文章于 2022-07-07 20:08:44 发布