思路:类似于摘结点法,利用尾指针(tail)把结点摘下来然后链在一起,然后返回头指针




#define _CRT_SECURE_NO_WARNINGS 1

//合并两个有序单链表,合并后依旧有序
#include<iostream>
using namespace std;

typedef int DataType;
typedef struct SListNode
{
DataType data; //数据
struct SListNode * next; //指向下一个结点的指针
}SListNode;

SListNode* CreateNode(DataType x) //创造结点
{
//1.先开辟空间 2.数据赋给data 3.指针置空
SListNode* NewNode = (SListNode *)malloc(sizeof (SListNode));
NewNode->data = x;
NewNode->next = NULL;

return NewNode;
}

void PushBack(SListNode * &ppHead, DataType Data )
{
//1.none 2.one and more
if (ppHead == NULL)
{
ppHead = CreateNode(Data );
}
else
{
//1.先找到尾结点 2.把新节点链起来
SListNode* cur = ppHead ;
while (cur->next)
{
cur = cur->next;
}
cur->next = CreateNode( Data);

}
}
//打印
void PrintSNodeList(SListNode *&ppHead)
{
while (ppHead )
{
printf( "%d->", ppHead ->data);
ppHead = ppHead ->next;
}
cout << "NULL" << endl;
}

//合并两个有序单链表,合并后依旧有序
SListNode* Merge(SListNode * l1, SListNode* l2)
{
SListNode* newHead = NULL ; //新头结点
//临界情况
if (l1 == NULL)
return l2 ;
if (l2 == NULL)
return l1 ;
if (l1 ->data < l2->data) //先制造一个头
{
newHead = l1;
l1 = l1 ->next;
}
else
{
newHead = l2;
l2 = l2 ->next;
}
SListNode* tail = newHead; //利用尾指针进行摘结点,

while (l1 && l2) //当l1和l2两个链表都还有值时。
{
if (l1 ->data < l2->data) //链入新的合并链表中
{
tail->next = l1;
tail = tail->next;
l1 = l1 ->next;
}
else
{
tail ->next= l2;
tail = tail->next;
l2 = l2 ->next;
}
}

if (l1 ) //如果l1还有剩余的结点
tail->next = l1;
if (l2 ) //l2还有剩余的结点
tail->next = l2;

return newHead;
}

void Test()
{
SListNode* pHead1 = NULL ;
SListNode* pHead2 = NULL ;
PushBack(pHead1, 1);
PushBack(pHead1, 3);
PushBack(pHead1, 5);
PushBack(pHead1, 7);
PushBack(pHead1, 9);
PushBack(pHead1, 11);
PushBack(pHead2, 2);
PushBack(pHead2, 4);
PushBack(pHead2, 6);
PushBack(pHead2, 8);
SListNode* newHead= Merge(pHead1, pHead2);
PrintSNodeList(newHead);
}

int main()
{
Test();
system( "pause");
return 0;
}


合并两个有序单链表,合并后依旧有序_数据



如果有什么不对的地方,希望能够指出,大家一起学习,谢谢了。