public class LinkList { public Node head; public LinkList() { head = new Node(); head.next = null; } //尾插法 public void createByTail(int[] arr, int n) { Node tail = head; for(int i=0; i<n; i++) { Node c = new Node(arr[i]); tail.next = c; tail = c; } tail.next = null; } //头插法 public void createByHead(int[] arr, int n) { head.next = null; for(int i=0; i<n; i++) { Node c = new Node(arr[i]); c.next = head.next; head.next = c; } } public void display() { Node p = head.next; while(p != null) { if(p.next != null) System.out.print(p.data + "->"); else System.out.println(p.data); p = p.next; } } //删除单链表中元素最大的节点 public void delMaxNode() { Node p = head.next, pre = head, maxp = head.next, maxpre = head; while(p != null) { if(p.data > maxp.data) { maxp = p; maxpre = pre; } pre = p; p = p.next; } maxpre.next = maxp.next; display(); } //单链表元素排序 public void sort() { Node p = head.next.next; head.next.next = null; Node q, pre; while(p != null) { q = p.next; pre = head; while(pre.next != null && pre.next.data < p.data) { pre = pre.next; } p.next = pre.next; pre.next = p; p = q; } display(); } public static void main(String[] args) { int[] arr = new int[]{5,6,1,6,9,3,7,8}; LinkList list = new LinkList(); list.createByHead(arr, arr.length); list.display(); list.createByTail(arr, arr.length); list.display(); list.delMaxNode(); list.sort(); } } class Node { public int data; public Node next; public Node(){} public Node(int data) { this.data = data; } }
结果:
8->7->3->9->6->1->6->5 5->6->1->6->9->3->7->8 5->6->1->6->3->7->8 1->3->5->6->6->7->8
时间: 2024-10-07 11:54:00