//合并两个有序的单链表
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);
}
}
合并两个有序的单链表
最新推荐文章于 2024-08-20 17:53:30 发布