设有两个按元素递增有序的单链表A和B,编一程序将A和B表归并成一个新的递增有序的单链表C,不使用额外空间。
- #include <iostream>
- using namespace std;
- struct Node{
- int m_Data;
- Node *m_pNext;
- };
- Node* mergeLists(Node *pListA, Node *pListB)
- {
- if (pListA==NULL){
- return pListB;
- }
- else if(pListB==NULL){
- return pListA;
- }
- else{
- Node *pHead = NULL;
- if (pListA->m_Data < pListB->m_Data){
- pHead = pListA;
- pListA = pListA->m_pNext;
- }
- else{
- pHead = pListB;
- pListB = pListB->m_pNext;
- }
- Node *pNode = pHead;
- while (pListA && pListB){
- if (pListA->m_Data < pListB->m_Data){
- pNode->m_pNext = pListA;
- pListA = pListA->m_pNext;
- }
- else{
- pNode->m_pNext = pListB;
- pListB = pListB->m_pNext;
- }
- pNode = pNode->m_pNext;
- }
- if (pListA){
- while (pListA){
- pNode->m_pNext = pListA;
- pListA = pListA->m_pNext;
- pNode = pNode->m_pNext;
- }
- }
- else if (pListB){
- while (pListB){
- pNode->m_pNext = pListB;
- pListB = pListB->m_pNext;
- pNode = pNode->m_pNext;
- }
- }
- return pHead;
- }
- }
- void printList(Node *pHead)
- {
- bool bEmpty = true;
- while (pHead){
- bEmpty = false;
- cout<<pHead->m_Data<<"->";
- pHead = pHead->m_pNext;
- }
- if (!bEmpty){
- cout<<"NULL"<<endl;
- }
- }
- int main()
- {
- Node nodeA5 = {4, NULL};
- Node nodeA4 = {4, &nodeA5};
- Node nodeA3 = {3, &nodeA4};
- Node nodeA2 = {1, &nodeA3};
- Node nodeA1 = {1, &nodeA2};
- Node nodeA0 = {0, &nodeA1};
- Node *pHeadA = &nodeA0;
- Node nodeB5 = {5, NULL};
- Node nodeB4 = {4, &nodeB5};
- Node nodeB3 = {3, &nodeB4};
- Node nodeB2 = {2, &nodeB3};
- Node nodeB1 = {2, &nodeB2};
- Node nodeB0 = {1, &nodeB1};
- Node *pHeadB = &nodeB0;
- cout<<"Linked List A: "<<endl;
- printList(pHeadA);
- cout<<"Linked List B: "<<endl;
- printList(pHeadA);
- Node *pHead = mergeLists(pHeadA, pHeadB);
- cout<<"Merged List A+B: "<<endl;
- printList(pHeadA);
- }