本文共 1630 字,大约阅读时间需要 5 分钟。
public class LinkedTest { public static void main(String[] args) { Node headNode1 = null; Node headNode2 = null; Node currNode1 = null; Node currNode2 = null; // 构造有序链表1 有序链表2 for (int i = 10; i >= 0; i--) { if (i % 2 == 0) { currNode1 = new Node(headNode1, i); headNode1 = currNode1; } else { currNode2 = new Node(headNode2, i); headNode2 = currNode2; } } System.out.print("有序链表1 -- "); print(headNode1); System.out.print("有序链表2 -- "); print(headNode2); System.out.print("合并有序链表 -- "); print(merage(headNode1, headNode2)); } // 将两个有序链表合为一个有序链表,使用递归的过程 public static Node merage(Node n1, Node n2) { if (n1 == null) { return n2; } if (n2 == null) { return n1; } Node resNode = null; if (n1.data > n2.data) { resNode = n2; resNode.next = merage(n1, n2.next); } else { resNode = n1; resNode.next = merage(n1.next, n2); } return resNode; } // 打印输出链表 public static void print(Node n) { if (n == null) { System.out.println("链表为空"); return; } for (Node node = n; node != null; node = node.next) { System.out.print(node.data + " "); } System.out.println(); }}class Node { Node next; int data; public Node(Node next, int data) { super(); this.next = next; this.data = data; }}
转载地址:http://uwkin.baihongyu.com/