码迷,mamicode.com
首页 > 编程语言 > 详细

剑指offer-面试题25-合并两个排序的链表-链表

时间:2019-11-21 14:21:52      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:include   ios   out   space   sharp   next   namespace   试题   pac   

/*
题目:
	输入两个递增排序的链表,合并这两个链表并使新的链表中的节点依然是递增排序。
	返回新链表的头节点。
*/
/*
思路:
	1、返回的链表的头节点为两个链表中头节点数值更小的为链表1。
	2、进行比较
	3、判断链表2的节点是否为空,若不为空则全部加到链表1的尾部。
*/
#include <iostream>
#include<cstdlib>

using namespace std;

struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};

ListNode* Merge(ListNode* pHead1, ListNode* pHead2){
    if(pHead1 == nullptr) return pHead2;
    if(pHead2 == nullptr) return pHead1;
    ListNode* pNode = nullptr;
    ListNode* qNode = nullptr;
    ListNode* temp = nullptr;
    ListNode* head = nullptr;
    if(pHead1->val < pHead2->val){
        pNode = pHead1;
        qNode = pHead2;
        head = pHead1;
    }else{
        pNode = pHead2;
        qNode = pHead1;
        head = pHead2;
    }
    while(pNode->next != nullptr && qNode != nullptr){
        if(pNode->next->val <= qNode->val){
            pNode = pNode->next;
        }else{
            temp = pNode->next;
            pNode->next = qNode;
            qNode = qNode->next;
            pNode->next->next = temp;
        }
    }
    if(pNode->next == nullptr){
        pNode->next = qNode;
    }
    return head;
}

int main()
{
    ListNode *node6 = new ListNode(6);
    ListNode *node5 = new ListNode(5);
    ListNode *node4 = new ListNode(4);
    ListNode *pHead2 = new ListNode(1);
    ListNode *node3 = new ListNode(5);
    ListNode *node2 = new ListNode(2);
    ListNode *node1 = new ListNode(2);
    ListNode *pHead1 = new ListNode(0);
    pHead1->next = node1;
    node1->next = node2;
    node2->next = node3;
    node3->next = nullptr;
    pHead2->next = node4;
    node4->next = node5;
    node5->next = node6;
    node6->next = nullptr;

    ListNode* pHead = Merge(pHead1,pHead2);
    cout<<"answer"<<endl;
    while(pHead != nullptr){
        cout<<pHead->val<<endl;
        pHead = pHead->next;
    }


    cout << "Hello world!" << endl;
    return 0;
}

   

剑指offer-面试题25-合并两个排序的链表-链表

标签:include   ios   out   space   sharp   next   namespace   试题   pac   

原文地址:https://www.cnblogs.com/buaaZhhx/p/11904908.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!