合并两个有序的单链表
来源:互联网 发布:c语言strcmp函数 编辑:程序博客网 时间:2024/06/16 06:26
//合并两个有序的单链表public class MergeList{public static class Node{ public int value; public Node next; public Node(int data) { this.value=data; }}//合并两个有序的单链表public static Node mergeList(Node head1,Node head2){ if(head1==null&&head2==null) { return null; }else if(head1==null) { return head2; }else if(head2==null) { return head1; } //记录两个链表的头结点 Node head=head1.value<head2.value?head1:head2; Node cur1=head==head1? head1:head2; Node cur2=head==head1? head2:head1; Node pre=null; //记录新排序链表的前一个节点 Node next=null; while(cur1!=null&&cur2!=null) { if(cur1.value<=cur2.value) { pre=cur1; cur1=cur1.next; }else { next=cur2.next; pre.next=cur2; cur2.next=cur1; pre=cur2; cur2=next; //cur2向后移动一个节点 } } pre.next=cur1==null?cur2:cur1; //连接其中一个链表没有遍历完的节点 return head; } //打印链表的内容 public static void PrintList(Node head) { while(head!=null) { System.out.print(head.value+" "); head=head.next; } System.out.println(); } public static void main(String[]args){ //System.out.println("Hello"); Node head1=new Node(0); head1.next=new Node(2); head1.next.next=new Node(3); head1.next.next.next=new Node(7); Node head2=new Node(1); head2.next=new Node(3); head2.next.next=new Node(5); head2.next.next.next=new Node(7); head2.next.next.next.next=new Node(9); Node mode=mergeList(head1,head2); PrintList(mode); } }
阅读全文
0 0
- 两个有序单链表的合并&两个有序数组的合并
- 两个有序单链表的合并
- 合并两个有序的单链表
- 合并两个有序的单链表
- 合并两个有序的单链表
- 合并两个有序的单链表
- 合并两个有序的单链表
- 合并两个有序的单链表
- 合并两个有序的单链表
- 合并两个有序的单链表
- 合并两个有序单链表
- 合并两个有序单链表
- 合并两个有序单链表
- 两个有序单链表合并
- 合并两个有序单链表
- 合并两个有序单链表
- 合并两个有序单链表
- 合并两个有序单链表
- UE4 HTC VIVE
- 关于栈帧的两道题型
- Jenkins+SVN+Maven自动化部署环境搭建
- 1701H2王建瑜 11.9 连续第四天
- 虚拟内存与物理内存详解
- 合并两个有序的单链表
- 多个视频,重复循环播放的解决方式
- Linux安装RocketMQ
- opencv把视频的每一帧保存为图片
- 获取textview的行数
- 第十一周-项目2
- LeetCode解题整理
- 移动端fixed + Input 调用键盘的时候fixed无效问题(css解决)
- 如何修改PHP上传文件大小的限制