#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct Node
{
int data;
struct Node *next;
}lnode, *pnode;
//********建立链表*******
pnode create_list()
{
int len;
int i;
int val;
pnode pHead = (pnode)malloc(sizeof(lnode));
if (!pHead)
{
cout << "分配失败" << endl;
exit(-1);
}
///***********ptail为指向尾节点,ptail=phead 是其初始,接下来会添加节点************
pnode pTail=pHead;
pTail->next = NULL;
cout << "请输入链表节点数:len=";
cin >> len;
for (i = 0; i<len; i++)
{
cout << "请输入第" << i + 1 << "个节点" << endl;
cin >> val;//val存放着节点的值
pnode pNew = (pnode)malloc(sizeof(lnode));
if (!pNew)
{
cout << "分配失败" << endl;
exit(-1);
}
pNew->data = val;
pTail->next = pNew;
pNew->next = NULL;
pTail = pNew;
}
return pHead;
}
//遍历链表
int traverse_list(pnode pHead)
{
pnode p = pHead->next;//将p指向首节点
while (p)
{
cout<<p->data << endl;
p=p->next;
}
cout << endl;
return 0;
}
///释放链表
void delete_list(pnode pHead)
{
delete pHead;
cout << "释放成功" << endl;
}
int main()
{
pnode pHead = NULL;
pHead = create_list();
//pHead=(pnode)malloc(sizeof(lnode));
traverse_list(pHead);
delete_list(pHead);
system("pause");
return 0;
}