JAVA链表测试代码
测试模板
class ListNode { // 链表类 int val; ListNode next = null; public ListNode(int val) { this.val = val; } } class Solution { public static void Myprint(ListNode t1) // 输出链表 { while (t1 != null) { System.out.println(t1.val); t1 = t1.next; } } //这里可写相关操作函数 public static void main(String[] args) { ListNode t1 = new ListNode(1); ListNode t2 = new ListNode(2); ListNode t3 = new ListNode(3); ListNode t4 = new ListNode(4); ListNode t5 = new ListNode(5); t1.next = t2; t2.next = null; System.out.println("--------链表t1-------"); Myprint(t1); t3.next = t4; t4.next = t5; t5.next = null; System.out.println("--------链表t3-------"); Myprint(t3); //相关操作函数 } }
例子:合并两个排序的链表
class ListNode { // 链表类 int val; ListNode next = null; public ListNode(int val) { this.val = val; } } class Solution { public static void Myprint(ListNode t1) // 输出链表 { while (t1 != null) { System.out.println(t1.val); t1 = t1.next; } } public static ListNode Merge(ListNode list1, ListNode list2) { // 两个链表的归并排序 // 归并排序的思想 if (list1 == null) { return list2; } if (list2 == null) { return list1; } ListNode head = new ListNode(-1); ListNode list3 = head; while (list1 != null && list2 != null) { if (list1.val < list2.val) { list3.next = list1; list1 = list1.next; } else { list3.next = list2; list2 = list2.next; } list3 = list3.next; } while (list1 != null) { list3.next = list1; list1 = list1.next; list3 = list3.next; } while (list2 != null) { list3.next = list2; list2 = list2.next; list3 = list3.next; } return head.next; } public static void main(String[] args) { ListNode t1 = new ListNode(1); ListNode t2 = new ListNode(2); ListNode t3 = new ListNode(3); ListNode t4 = new ListNode(4); ListNode t5 = new ListNode(5); t1.next = t2; t2.next = null; System.out.println("--------链表t1-------"); Myprint(t1); t3.next = t4; t4.next = t5; t5.next = null; System.out.println("--------链表t3-------"); Myprint(t3); System.out.println("--------t1与t3合并的链表-------"); ListNode r = Merge(t1, t3); Myprint(r); } }