好久没碰指针和链表了,先从基础题刷起。(面试题也有很多链表的操作,包括程序改错也是有指针的)
持续更新中。
#include<stdio.h>
#include<iostream>
using namespace std;
struct ListNode{
    int val;
    struct ListNode *next;
    ListNode(int x):val(x),next(NULL){}
};
class Solution {
public:
    ListNode* Merge(ListNode* pHead1,ListNode* pHead2)
    {
        if(!pHead1) return pHead2;
        else if(!pHead2) return pHead1;
        ListNode *p,*q;
        p=new ListNode(NULL);
        q=p;
        while(pHead1||pHead2)
        {
            if(!pHead1&&pHead2)
            {
                p->next=pHead2;
                p=pHead2;
                break;
            }
            if(!pHead2&&pHead1)
            {
                p->next=pHead1;
                p=pHead1;
                break;
            }
            if(pHead1->val<pHead2->val)
            {
                p->next=pHead1;
                p=pHead1;
                pHead1=pHead1->next;
            }
            else
            {
                p->next=pHead2;
                p=pHead2;
                pHead2=pHead2->next;
            }
        }
        return q->next;
    }
    ListNode* CreatList(ListNode *pHead,int n)
    {
        if(n==0) return NULL;
        ListNode *p,*q;
        pHead=new ListNode(NULL);
        p=pHead;
        cin>>p->val;
        int x;
        while(--n)
        {
            cin>>x;
            q=new ListNode(x);
            p->next=q;
            p=q;
        }
        return pHead;
    }
};
int main()
{
    int n,m;
    Solution so;
    ListNode *L1,*L2;
    cin>>n;
    L1=so.CreatList(L1,n);
    cin>>m;
    L2=so.CreatList(L2,m);
    ListNode *ans=so.Merge(L1,L2);
    while(ans)
    {
        printf("%d\t",ans->val);
        ans=ans->next;
    }
    return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u010579068/article/details/48268043