用C/C++实现单向列表创建与输出链表存储值的操作
// 链表.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
//创建一个链表节点
struct Node {
int data;
Node * pNext;
};
//创建一个单向链表
Node * creat_list(){
int val;
int len;
Node * pHead = (Node *)malloc(sizeof(Node));
Node * pTail = pHead;
pTail->pNext = NULL;
if (pHead == NULL)
{
cout << "分配内存失败" <<endl;
exit(-1);
}
cout << "请输入链表的大小:len = ";
cin >> len;
for (int i = 0; i < len; ++i)
{
Node * pNew = (Node *)malloc(sizeof(Node));
if (pNew == NULL)
{
cout << "内存分配失败" << endl;
exit(-1);
}
cout << "请输入节点的值:";
cin >> val;
pNew->data = val;
pTail->pNext = pNew;
pNew->pNext = NULL;
pTail = pNew;
}
return pHead;
}
//输出链表的所有值
void traverse_list(Node * pHead){
Node * p = pHead->pNext;
while (p != NULL)
{
cout << p->data <<endl;
p = p->pNext;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
Node * pHead = creat_list();
traverse_list(pHead);
system("pause");
return 0;
}