合并两个有序链表
来源:互联网 发布:win10打不开任何软件 编辑:程序博客网 时间:2024/06/11 08:45
链表的基本构造:
public class ListNode {public int val;public ListNode next;public ListNode(int val, ListNode next) {super();this.val = val;this.next = next;}public ListNode(int val) {super();this.val = val;}public static ListNode arrayToList(int[] arr) {ListNode head = new ListNode(0);ListNode p = head;for(int value : arr){p.next = new ListNode(value);p = p.next;}return head.next;}public static void printList(ListNode head){ListNode p = head;while(p != null){System.out.print(p.val + " ");p = p.next;}System.out.println();}}
2.两个链表的合并代码:
public class 合并两个有序链表 {public static void main(String[] args) {int[] array1 = { 1, 3, 7, 8 };ListNode head1 = ListNode.arrayToList(array1);ListNode.printList(head1);int[] array2 = { 2, 4, 5, 9 };ListNode head2 = ListNode.arrayToList(array2);ListNode.printList(head2);ListNode.printList(mergeList(head1, head2));}private static ListNode mergeList(ListNode head1, ListNode head2) {if (head1 == null && head2 == null) {return null; // 如果两个链表都为空}if (head1 == null) {return head2;}if (head2 == null) {return head1;}/** * 新链表的头结点 一开始,我们让current结点指向head1和head2中较小的数据,得到head结点 */ListNode head;ListNode current;if (head1.val < head2.val) {head = head1;current = head1;head1 = head1.next;} else {head = head2;current = head2;head2 = head2.next;}while (head1 != null && head2 != null) {if (head1.val < head2.val) {current.next = head1; // 新链表中,current指针的下一个结点对应较小的那个数据current = current.next; // current指针下移head1 = head1.next;} else {current.next = head2;current = current.next;head2 = head2.next;}}// 合并剩余的元素if (head1 != null) {current.next = head1;}if (head2 != null) {current.next = head2;}return head;}}
阅读全文
0 0
- 有序的合并两个有序链表
- 两个有序链表合并为有序
- 合并两个有序链表
- 合并两个有序链表
- 合并两个有序链表
- 合并两个有序链表
- 合并两个有序链表
- 合并两个有序链表
- 合并两个有序链表
- 合并两个有序链表
- 两个有序链表合并
- 合并两个有序链表
- 两个有序链表合并
- 合并两个有序链表
- 合并两个有序链表
- 两个有序链表合并
- 合并两个有序链表
- 合并两个有序链表
- 【cc2541历程】ds18b20发送数值到App
- 微信分享时没有缩略图时的解决方案!
- Centos 6.9 在线YUM报错解决
- Java中this和super的用法总结
- log4j使用实例
- 合并两个有序链表
- 第三方登陆原理
- POJ2155_Matrix_二维树状数组
- Linux sed
- 如果list中的对像的编号相同就把对像合并,并将数量相加
- jquery根据字符串长度限定,截取字符串
- 【Unet】Unet Network Messages
- C# 获取应用程序物理地址(运行DLL的物理地址)
- 验证码