首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

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

2012-11-01 
单向循环链表在线求教C/C++ code#include stdafx.h#include iostreamusing namespace stdstruct Node

单向循环链表在线求教

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;
}

热点排行