#include <iostream>
#include <malloc.h>
#include <stdlib.h>
using namespace std;
//节点
typedef struct Node
{
int date;//数据域
Node * pNext;//指针域
}NODE, * PNODE;
PNODE creat(void);//动态的创建一个链表
bool print(PNODE);//输出链表的数据
bool insert(PNODE, int, int);//用法:insert(pHead, 2, 3);表示在第二个位置上插入数据3。
bool delet(PNODE, int);//用法:delet(pHead, 2);表示在删除第二个位置上的数据。
int count(PNODE);//返回链表的有效长度
程序的入口
int main()
{
PNODE pHead;
cout << "测试链表的创建:" << endl;
pHead = creat();
cout << "测试链表的输出:" << endl;
if (print(pHead))//测试输出是否成功
{
cout << "输出完毕!" << endl;
}
else
{
cout << "没有数据!" << endl;
}
cout << "测试返回链表的长度:" << endl;
cout << count(pHead) << endl;
cout << "测试插入链表:" << endl;
if (insert(pHead, 1, 1))
{
print(pHead);
}
else
{
cout << "插入失败!" << endl;
}
cout << "测试删除链表:" << endl;
if (delet(pHead, 3))
{
print(pHead);
}
else
{
cout << "删除失败!" << endl;
}
system("pause");
return 0;
}
PNODE creat(void)
{
int i, val, len;
PNODE pHead = (PNODE)malloc(sizeof(NODE));//动态的创建节点
if (NULL==pHead)//测试节点是否创建成功
{
cerr << "动态分配内存失败!" << endl;
system("pause");
exit(-1);//退出程序,必须包含头文件 stdlib.h
}
PNODE pTail = pHead;//Tail为尾节点
pTail->pNext = NULL;
cout << "请输入节点的个数:" << endl;
cout << "length = ";
cin >> len;
if (len<=0)
{
cout << "链表长度不能为负数或零!" << endl;
system("pause");
exit(-1);
}
for (i=0; i<len; ++i)
{
cout << "请输入节点的数据(整数):" << endl;
cout << "第" << i+1 << "个节点的数据:" << endl;
cout << "number = ";
cin >> val;
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if (NULL==pNew)
{
cerr << "动态分配内存失败!" << endl;
system("pause");
exit(-1);
}
pNew->date = val;
pTail->pNext = pNew;
pNew->pNext = NULL;
pTail = pNew;
}
return pHead;
}
bool print(PNODE pHead)
{
bool success = false;
for (; NULL!=pHead->pNext; pHead=pHead->pNext)
{
cout << pHead->pNext->date << " ";
success = true;
}
cout << endl;
return success;
}
int count(PNODE pHead)
{
int count = 0;
while (NULL!=pHead->pNext)
{
++count;
pHead = pHead->pNext;
}
return count;
}
bool insert(PNODE pHead, int postion, int val)
{
int success = false;
int i = 1;
if (postion<1 || postion>count(pHead)+1)
{
cout << "请输入有效的位置!" << endl;
system("pause");
exit(-1);
}
while (i<postion && NULL!=pHead->pNext)
{
pHead = pHead->pNext;
++i;
};
PNODE p = NULL;
p = pHead->pNext;
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if (NULL==pNew)
{
cerr << "动态分配内存失败!" << endl;
system("pause");
exit(-1);
}
pNew->date = val;
pNew->pNext = pHead->pNext;
pHead->pNext = pNew;
success = true;
return success;
}
bool delet(PNODE pHead, int postion)
{
int success = false;
int i = 1;
if (postion<1 || postion>count(pHead))
{
cout << "请输入有效的位置!" << endl;
system("pause");
exit(-1);
}
while (i<postion && NULL!=pHead->pNext)
{
pHead = pHead->pNext;
++i;
};
PNODE p = NULL;
p = pHead->pNext;
pHead->pNext = p->pNext;
free(p);
success = true;
return success;
}
自己写的一个链表,可能有bug
最新推荐文章于 2023-12-21 23:48:14 发布