[剑指offer][面试题17]合并两个排序的链表

来源:互联网 发布:北京方正软件技术学院 编辑:程序博客网 时间:2024/05/16 13:00

[2005腾讯笔试]不使用额外空间,将 A,B两链表的元素交叉归并

设有两个按元素递增有序的单链表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); }


原创粉丝点击