我正试图将一个单链表拆分为2个单链表。L1将获得l的30%的成员,l2将获得l的30%的成员。
#include <iostream>
using namespace std;
struct Node{
int data;
Node* pNext;
};
struct List{
Node* pHead, *pTail;
};
void CreateList(List &l){
l.pHead=l.pTail=NULL;
}
int Count(List l){
int i=0;
Node*p=l.pHead;
while (p){
i++;
p=p->pNext;
}
return i;
}
void RemoveList(List &l){
Node *p;
while (l.pHead){
p=l.pHead;
l.pHead=p->pNext;
delete p;
}
}
void Patition(List &l, List &l1, List &l2){
int t=Count(l)*0.3;
cout<<"t="<<t<<endl;
CreateList(l1);
CreateList(l2);
Node *p=l.pHead;
l1.pHead=p;
for (int i=0;i<t;i++)
p=p->pNext;
l1.pTail=p;
l.pHead=p->pNext;
p=l.pHead;
l2.pHead=p;
for (int i=0;i<t;i++)
p=p->pNext;
l2.pTail=p;
l.pHead=p->pNext;
RemoveList(l);
}
我使用下面的代码来测试你的函数:
int _tmain(int argc, _TCHAR* argv[])
{
List l;
CreateList(l);
l.pHead = new Node;
l.pHead->pNext = l.pTail;
Node *iterator = l.pHead;
// Initial linked list
for (int i = 0; i < 10; i++) {
Node *newNode = new Node;
newNode->pNext = iterator->pNext;
iterator->data = i;
iterator->pNext = newNode;
iterator = newNode;
}
List l1, l2;
Patition(l, l1, l2);
cout << Count(l);
cout << Count(l1);
cout << Count(l2);
return 0;
}
我发现的是,在你的Count函数中,你的结束条件是当p
是NULL时,但是在你的配分函数中,你不让你的链表更新,结束指向NULL。
我如何纠正这个问题是简单地修改你的配分函数为
void Patition(List &l, List &l1, List &l2){
int t = Count(l)*0.3;
cout << "t=" << t << endl;
CreateList(l1);
CreateList(l2);
Node *p = l.pHead;
l1.pHead = p;
for (int i = 0; i<t; i++)
p = p->pNext;
// Change
l.pHead = p->pNext;
p->pNext = l1.pTail;
//
p = l.pHead;
l2.pHead = p;
for (int i = 0; i<t; i++)
p = p->pNext;
// Change
l.pHead = p->pNext;
p->pNext = l2.pTail;
//
RemoveList(l);
}
这将保持每个链表的尾部指向pTail,而不会跳过原始链表中的任何节点。