复杂链表的复制第三步,我自己写了一个函数,易于理解。
把第二步得到的链表拆分成两个链表,奇数位置上的结点组成原始链表,偶数位置上的结点组成复制出来的链表。
示例代码如下:
#include <iostream>
using namespace std;
typedef struct ListNode{
int value;
struct ListNode* next;
}ListNode;
ListNode* CreateList(int nodeNumber){
ListNode* head=NULL;
ListNode* tail=NULL;
int value;
for(int i=0;i<nodeNumber;i++){
cin>>value;
ListNode* temp=new ListNode();
temp->value=value;
temp->next=NULL;
if(head==NULL){
head=temp;
tail=head;//尾插法
}else{
tail->next=temp;
tail=tail->next;
}
}
return head;
}
ListNode* ReconnectList(ListNode* pHead){
if(pHead==NULL)
return NULL;
ListNode* pNewHead=pHead->next;
ListNode* pNewTail=pNewHead;
ListNode* pTail=pHead;
if(pHead->next->next==NULL){ //原链表只有一个结点的情况
pHead->next=NULL;
}else{
int i=3;
ListNode* traPointer=pNewHead->next;//遍历合并的链表
while(traPointer!=NULL){
if(i%2!=0){ //奇数位置的结点属于原链表
pTail->next=traPointer;
pTail=pTail->next;
}else{
pNewTail->next=traPointer;
pNewTail=pNewTail->next;
}
traPointer=traPointer->next;
++i;
}
pTail->next=NULL;//结尾为NULL
}
return pNewHead;
}
void PrintList(ListNode* head){
if(head==NULL)
return;
ListNode *pNode=head;
while(pNode!=NULL){
std::cout<<pNode->value<<" ";
pNode=pNode->next;
}
std::cout<<std::endl;
}
void TestProgram26(){
int nodeNumber;
cin>>nodeNumber;
ListNode* head=CreateList(nodeNumber);
ListNode* newHead=ReconnectList(head);
PrintList(head);
PrintList(newHead);
}
运行结果截图: