Java建立單鏈表並直接選擇排序輸出
阿新 • • 發佈:2019-01-08
RT
寫Java也一年左右了,第一次用Java寫單鏈表。。。
廢話少說,程式碼如下:
import java.util.Scanner; public class Exp1 { public static void main(String[] args) { Node no = addNode(); P(no); P(sortNode(no)); } // 列印單鏈表 static void P(Node a) { a = a.next; while (a != null) { System.out.print(a.data + " "); a = a.next; } System.out.println(); } // 新增元素 static Node addNode() { Node head = new Node(0); Node t = null; t = head; System.out.println("輸入:"); Scanner sc = new Scanner(System.in); int a = sc.nextInt(); do { Node tail = new Node(); tail.data = a; tail.next = null; head.next = tail; head = tail; } while (sc.hasNext() && (a = sc.nextInt()) != -1); sc.close(); return t; } // 直接選擇排序單鏈表 static Node sortNode(Node head) { Node t = null; t = head; int min = 0; int temp = 0; Node p, q, m; p = q = m = head; while (p.next != null) { m = q = p.next; min = q.data; while (q != null) { if (q.data < min) { m = q; min = q.data; } q = q.next; } if (p.next != m) { temp = p.next.data; p.next.data = m.data; m.data = temp; } p = p.next; } return t; } } class Node { int data; Node next; public Node(int data) { this.data = data; next = null; } public Node() { } }