合并两个有序的单链表,合并之后的新链表依然有序

本文探讨如何将两个已排序的单链表合并为一个保持有序的新链表,详细阐述了合并过程及关键步骤。
摘要由CSDN通过智能技术生成
package com.zzb.datastructure.singlelist;

import java.io.Serializable;

/**
 * @Auther: Administrator
 * @Date: 2020/1/15 16:55
 * @Description:
 * 合并两个有序的单链表,合并之后的新链表依然有序
 */
public class MergeOrderSingleLinkedListTest {
    public static void main(String[] args) {
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);

        Node node4 = new Node(4);
        Node node5 = new Node(5);
        Node node6 = new Node(6);

        node1.setNext(node2);
        node2.setNext(node3);

        node4.setNext(node5);
        node5.setNext(node6);

        Node result = merge(node1,node4);

        while(result != null) {
            System.out.print(result.getData() + "\t");
            result = result.getNext();
        }
        /*
        1	2	3	4	5	6*/
    }

    private static Node merge(Node node1, Node node2) {
        // 判断需要合并
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以按照以下步骤来实现两个有序单链表合并链表: 1. 定义链表节点结构体,包含数据和指向下一个节点的指针。 ```c struct ListNode { int val; struct ListNode *next; }; ``` 2. 实现一个函数 `mergeTwoLists`,接收两个链表的头指针,返回合并后的链表头指针。 ```c struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) { // 如果两个链表中有一个为空,则直接返回另一个链表 if (l1 == NULL) return l2; if (l2 == NULL) return l1; // 定义一个链表的头指针和尾指针 struct ListNode dummy; struct ListNode *tail = &dummy; // 遍历两个链表,将较小值的节点插入到链表的尾部 while (l1 != NULL && l2 != NULL) { if (l1->val < l2->val) { tail->next = l1; l1 = l1->next; } else { tail->next = l2; l2 = l2->next; } tail = tail->next; } // 将剩余的节点插入到链表尾部 if (l1 != NULL) tail->next = l1; if (l2 != NULL) tail->next = l2; // 返回链表的头指针 return dummy.next; } ``` 这个函数会遍历两个链表,将较小值的节点插入到链表的尾部,最后返回链表的头指针。 可以使用以下代码测试这个函数的正确性: ```c int main() { struct ListNode l1_3 = {4, NULL}; struct ListNode l1_2 = {2, &l1_3}; struct ListNode l1_1 = {1, &l1_2}; struct ListNode l2_3 = {7, NULL}; struct ListNode l2_2 = {3, &l2_3}; struct ListNode l2_1 = {1, &l2_2}; struct ListNode *merged = mergeTwoLists(&l1_1, &l2_1); while (merged != NULL) { printf("%d ", merged->val); merged = merged->next; } printf("\n"); return 0; } ``` 输出应该为:`1 1 2 3 4 7`。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值