// 题目:合并两个增序链表
// 解法1:非递归的方法
public class Main {
public static void main(String[] args) {
ListNode n1 = new ListNode();
ListNode n2 = new ListNode();
ListNode n3 = new ListNode();
ListNode n4 = new ListNode();
ListNode t1 = new ListNode();
ListNode t2 = new ListNode();
ListNode t3 = new ListNode();
ListNode t4 = new ListNode();
n1.data = 1;
n2.data = 3;
n3.data = 5;
n4.data = 7;
t1.data = 2;
t2.data = 4;
t3.data = 6;
t4.data = 8;
n1.next = n2;
n2.next = n3;
n3.next = n4;
t1.next = t2;
t2.next = t3;
t3.next = t4;
ListNode result = mergeList(n1,t1);
while(result!=null){
System.out.println(result.data);
result = result.next;
}
}
public static ListNode mergeList(ListNode node1, ListNode node2) {
if(node1 == null){
return node2;
}
if(node2 == null){
return node1;
}
ListNode result;
ListNode temp; //返回链表中每次操作的结点
if(node1.data<node2.data){ //确定第一个返回的结点
result = node1;
temp = node1;
node1 = node1.next;
}else{
result = node2;
temp = node2;
node2 = node2.next;
}
while(node1!=null && node2!=null){ //一直比较,知道一个链表被遍历完
if(node1.data<node2.data){
temp.next = node1;
temp = temp.next;
node1 = node1.next;
}else{
temp.next = node2;
temp = temp.next;
node2 = node2.next;
}
}
while(node1!=null){ //把没有遍历完的部分连接到结果之后
temp.next = node1;
break;
}
while(node2!=null){
temp.next = node2;
break;
}
return result;
}
}
// 解法2:递归的方法
public class Main {
public static void main(String[] args) {
ListNode n1 = new ListNode();
ListNode n2 = new ListNode();
ListNode n3 = new ListNode();
ListNode n4 = new ListNode();
ListNode t1 = new ListNode();
ListNode t2 = new ListNode();
ListNode t3 = new ListNode();
ListNode t4 = new ListNode();
n1.data = 1;
n2.data = 3;
n3.data = 5;
n4.data = 7;
t1.data = 2;
t2.data = 4;
t3.data = 6;
t4.data = 8;
n1.next = n2;
n2.next = n3;
n3.next = n4;
t1.next = t2;
t2.next = t3;
t3.next = t4;
ListNode result = mergeList(n1,t1);
while(result!=null){
System.out.println(result.data);
result = result.next;
}
}
public static ListNode mergeList(ListNode node1, ListNode node2) {
if(node1 == null){ //如果一个遍历完了就返回另一个
return node2;
}
if(node2 == null){
return node1;
}
ListNode result;
if(node1.data<node2.data){ //找到当前节点比较小的作为返回
result = node1;
node1 = node1.next;
}else{
result = node2;
node2 = node2.next;
}
result.next = mergeList(node1,node2); //递归的判断返回结点的下一节点
return result;
}
}
剑指offer 17. 合并两个排序的链表
最新推荐文章于 2024-08-19 16:01:20 发布