拆分单链表

Splitting Singly Linked List

我正在尝试将一个单向链表拆分为 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 而不会跳过原始链表中的任何节点。