读书人

单向循环链表在线求教解决方案

发布时间: 2012-11-01 11:11:33 作者: rapoo

单向循环链表在线求教

C/C++ code
#include "stdafx.h"#include <iostream>using namespace std;struct Node {    Node()    {        num = 0;        flag = 'S';        next = NULL;    }    ~Node()    {        delete next;        next = NULL;    }    int num;    char flag;     Node* next;};int main(int argc, char* argv[]){    int N = 1;    Node *pHead;    pHead = new Node;    Node *p = pHead;    cin>>N;    for (int i = 0;i<N;i++)    {        p = new Node;        p->num = i+1;        p->flag = 'S';        p->next = pHead;        p = p->next;            }    p = pHead;    p = p->next;    cout<<p->num<<endl;    return 0;}


[解决办法]
为什么用struct,不用class了

退出for以后p就和phead指向同一个地方了
[解决办法]

#include <iostream>
using namespace std;

struct Node
{
Node()
{
num = 0;
flag = 'S';
next = NULL;
}
~Node()
{
delete next;
next = NULL;
}
int num;
char flag;
Node* next;
};

int main(int argc, char* argv[])
{
int N = 1;
Node *pHead;
pHead = new Node;
pHead->next=pHead;

Node *p;
cin>>N;

for (int i = 0;i<N;i++)//头插法
{
p = new Node;
p->num = i+1;
p->flag = 'S';
p->next = pHead->next;
pHead->next=p;
}
cout<<p->num<<endl;

return 0;
}

读书人网 >C++

热点推荐