自学的C语言可能算法比较垃圾,希望能够指出更好的算法,
以下是C语言链表的一些基本操作,把它弄成链表功能的集合:
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
typedef struct student
{
int num;
struct student *next;
}st;
st *creat(int n);//创立节点
void print(st *head);//打印节点
void add(st *head1, int n);//添加节点
void detele(st *head, int n);//删除节点
void creect(st *head, int n);//修改节点
void search(st * head, int temp);//查找节点
int main()
{
int n,m,o,temp,b,lo;
st *head;
cout << "输入创建节点的个数:\n";
cin >> n;
head = creat(n);
cout << "1.添加节点\n";
cout << "2.打印节点\n";
cout << "3.删除节点\n";
cout << "4.修改节点\n";
cout << "5.查找节点\n";
cout << "0.退出系统\n";
cout << "\n请输入指令: ( 0 到 9 ) \n";
while (1)
{
cin >> m;
if (m == 0) { cout << "成功退出!!\n"; break; }
switch (m)
{
case 1: { cout << "输入添加节点的位置:\n"; cin >> o; add(head,o); break; }
case 2: {cout << "打印节点数据如下 :\n"; print(head); break; }
case 3: { cout << "输入删除节点的位置: \n"; cin >> b; detele(head, b); break; }
case 4: {cout << "输入修改节点的位置:\n"; cin >> lo; creect(head, lo); break; }
case 5: {cout << "输入查找的值:\n"; cin >> temp; search(head, temp); break; }
default: {cout << "没有这个选项,请重新输入:\n"; break; }
}
}
return 0;
}
st *creat(int n)
{
st *head, *end, *node;
head = (st*)malloc(sizeof(st));
end = head;
printf("请输入节点数据:");
for (int i = 0; i < n; i++)
{
node = (st*)malloc(sizeof(st));
cin >> node->num;
end->next = node;
end = node;
}
end->next = NULL;
return head;
}
void print(st *head)
{
st *p = head->next;
while (p)
{
printf("%d ", p->num);
p = p->next;
}
}
void add(st *head1, int n)
{
st *t = head1;
int i = 1;
while (i < n&&t != NULL)
{
t = t->next;
i++;
}
if (t != NULL)
{
st *node = (st*)malloc(sizeof(st));
cout << "\n请输入节点数据: \n";
cin >> node->num;
node->next = t->next;
t->next = node;
}
else
{
cout << "该节点不存在!!!!!";
}
}
void detele(st *head, int n)
{
st *t;
int i = 0;
t = head;
while (i < n&&t != NULL)
{
head = t;
t = t->next;
i++;
}
if (t != NULL)
{
head-> next = t ->next;
free(t);
}
else
{
cout << "该节点不存在!!!!!";
}
}
void creect(st *head, int n)
{
st *t = head;
int i = 0;
while (i < n&&t != NULL)
{
t = t->next;
i++;
}
if (t != NULL)
{
cout << "\n输入新建节点的数据:\n";
cin >> t->num;
}
else
{
cout << "该节点不存在!!!!!";
}
}
void search(st * head, int temp)
{
st *t = head;
int i = 0;
while (t->num != temp && t != NULL)
{
t = t->next;
i++;
}
if (t != NULL)
{
cout << "\n该节点的位置为\n: "<<i;
}
else
{
cout << "该节点不存在!!!!";
}
}