1、创建一个带头结点的单链表(头指针为head),且遍历此链表(输出链表中各结点的值);
2、查找单链表中的第i个结点,并输出结点元素的值;
3、在单链表中的第i个结点前插入一个结点值为e的正整数(从外部输入);
4、删除单链表中的第j个结点;
5、将单链表中的各结点就地逆序(不允许另建一个链表);
#include
#include
#include
using namespace std;
typedef struct lnode
{
int date;
struct lnode
next;
}linklist;
linklist* creatlist(int m)
{
linklistp1, p2, head;
p1 = p2 = head = (linklist
)malloc(sizeof(lnode));
head->next = NULL;
while(m!=0)
{
cin >> p1->date;
p1 = (linklist
)(malloc(sizeof(lnode)));
p2->next= p1;
p2 = p1;
m–;
}
p1->next = NULL;
return head;
}
void bianlilist(linklist
head)
{
linklistp1;
p1 = head;
do
{
cout << p1->date << " ";
p1 = p1->next;
} while (p1->next != NULL);
}
void search(linklist
head)
{
linklist* p;
p = head;
int n;
cin >> n;
while (n != 1)
{
p = p->next;
n–;
}
cout << p->date;
}
void insert(linklisthead,int z)
{
int n,m;
linklist
p1,p2;
cin >> n>>m;
p1 = (linklist
)(malloc(sizeof(lnode)));
p1->date =m;
p2 = head;
if (n == 1)
{
p1->next = p2;
head= p1;
}
else
if (n == z)
{
while (m>1)
{
p2 = p2->next; m–;
};
p2->next = p1;
p1->next = NULL;
}
else
{
while (n - 1 >1)
{
p2 = p2->next; n–;
}
p1->next = p2->next;
p2->next = p1;
}
bianlilist(head);
}
void del(linklisthead,int z)
{
int m;
linklist
p2;
p2 = head;
cin >> m;
if (m == 1)
head = head->next;
else
if (m == z)
{
while(m>1)
{
p2 = p2->next; m–;
} ;
p2->next = NULL;
}
else
{
while(m>2)
{
p2 = p2->next; m–;
}
p2->next = p2->next->next;
}
bianlilist(head);
}
void sort1(linklist*head,int m)
{
linklist *New, *old, tag;
int y = 1;
New = head;
old = New->next;
while (y<m)
{
tag =old->next;
old->next= New;
New = old;
old = tag;
y++;
}
head->next= old;
bianlilist(New);
}
int main()
{
int n, m;
linklist
head;
cout << “创建单链表,请输入数据长度和数据\n”;
cout << “遍历链表请输入 :1\n”;
cout << “查找节点请输入 :2 \n”;
cout << “插入节点请输入 :3\n”;
cout << “删除单链表请输入 :4\n”;
cout << “逆序单链表请输入 :5\n”;
cin >> m;
head=creatlist(m);
cout << “请输入操作数:”;
cin >> n;
switch (n)
{
case 1:bianlilist(head); break;
case 2:cout << “输入要查找的序号:”; search(head); break;
case 3:cout << “输入要插的位置和插入的值:”; insert(head,m); break;
case 4:cout << “输入要删除的序号:”; del(head,m); break;
case 5:sort1(head,m); break;
}
}
03在这里插入图片描述
05在这里插入图片描述
01
![01![](https://img-blog.csdnimg.cn/20200315171458208.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTk2NTM1OA==,size_16,color_FFFFFF,t_70)04在这里插入图片描述
02在这里插入图片描述

posted on 2020-03-15 17:18  Beyond2019  阅读(806)  评论(0编辑  收藏  举报