合并两个有序的单链表

题目:给定两个有序单链表的头节点head1和head2,请合并两个有序链表,合并后的链表依然有序,并返回合并后链表的头节点

class node:
    def __init__(self,value):
        self.value = value
        self.next = None
        
def merge(head1,head2):
    if head1 == None or head2 == None:
        if head2 == None:
            return head1  
        else:
            return head2
        
    head = head1 if head1.value < head2.value else head2
    
    if head == head1:
        cur1 = head1
        cur2 = head2
    else:
        cur1 = head2
        cur2 = head1
        
    pre = None
    
    while cur1!=None and cur2!=None:
        
        if cur1.value <= cur2.value:
            pre = cur1
            cur1 = cur1.next
            
        else:
            next_ = cur2.next
            pre.next = cur2
            cur2.next = cur1
            pre = cur2
            cur2 = next_
            
    
    if cur2 == None:
        pre.next = cur1
    else:
        pre.next = cur2
    
    return head

 

要实现两个有序单链表合并,可以按照以下步骤进行: 1. 创建一个新的链表头节点,并用一个变量newHead指向它。 2. 创建两个当前节点变量,分别指向两个有序链表的头节点,命名为list1和list2。 3. 使用一个循环遍历两个有序链表,直到其中一个链表为空。 4. 在循环内部,比较list1和list2当前节点的值大小。 - 如果list1的值小于等于list2的值,将list1的节点连接到新链表中,并将list1指针后移。 - 如果list2的值小于list1的值,将list2的节点连接到新链表中,并将list2指针后移。 5. 循环结束后,将剩余未遍历完的链表连接到新链表的末尾。 6. 返回新链表的头节点newHead。 以下是Java代码示例: ```java class Node { int value; Node next; public Node(int value) { this.value = value; } } public class Main { public static Node mergeLinkedLists(Node list1, Node list2) { if (list1 == null) { return list2; } if (list2 == null) { return list1; } Node newHead; if (list1.value <= list2.value) { newHead = list1; list1 = list1.next; } else { newHead = list2; list2 = list2.next; } Node current = newHead; while (list1 != null && list2 != null) { if (list1.value <= list2.value) { current.next = list1; list1 = list1.next; } else { current.next = list2; list2 = list2.next; } current = current.next; } if (list1 != null) { current.next = list1; } if (list2 != null) { current.next = list2; } return newHead; } public static void main(String[] args) { // 创建第一个有序链表 Node list1 = new Node(1); list1.next = new Node(3); list1.next.next = new Node(5); // 创建第二个有序链表 Node list2 = new Node(2); list2.next = new Node(4); list2.next.next = new Node(6); // 合并链表 Node mergedList = mergeLinkedLists(list1, list2); // 打印合并后链表的值 Node current = mergedList; while (current != null) { System.out.print(current.value + " "); current = current.next; } } } ``` 运行上述代码,将输出合并后链表的值:1 2 3 4 5 6。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值