zoukankan      html  css  js  c++  java
  • 剑指offer-面试题25-合并两个排序的链表-链表

    /*
    题目:
    	输入两个递增排序的链表,合并这两个链表并使新的链表中的节点依然是递增排序。
    	返回新链表的头节点。
    */
    /*
    思路:
    	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;
    }
    

       

  • 相关阅读:
    Python正则表达式指南
    emacs 常用命令与配置
    将代码转换为语法高亮的HTML
    UML 用例图
    Sql Server 2005函数学习(转)
    实现ASP.NET程序性能目标的几种方法转载http://www.wzsky.net/html/Program/net/39759.html
    浅淡SqlServer的Top与Oracle的RowNum 转载自http://www.cnblogs.com/liguangxi8/archive/2010/05/21/1740708.html
    存储过程权限和订单类别
    UrlRewrite(Url重写技术)
    Jquery ajax多级联动
  • 原文地址:https://www.cnblogs.com/buaaZhhx/p/11904908.html
Copyright © 2011-2022 走看看