对于链表意义的理解:链表包含head(头节点)node(节点)由上一个节点包含下一个节点的地址从而实现连接。
实现代码
#include<bits/stdc++.h>//万能头文件
using namespace std;
typedef struct node_{
int value;
struct node_ *next;
}node;
bool Yes_node(node *head)
{
if (head == NULL || head->next == NULL) {
return false; // 如果链表为空或只有一个节点,则直接返回
}
return true;
}
node* creat_node(int value)//创立新的节点
{
node *p = (node*)malloc(sizeof(node));
p->value=value;
p->next=NULL;
return p;
}
node* front_insert_node(node *head,int value)//在前面插入
{
node *new_head = creat_node(value);
new_head->next=head;
return new_head;
}
node* insert_node(node *head,int value,int point)//根据位置直接插入
{
int i;
node *cur=head,*pre;
if(point==0){
head = front_insert_node(head,value);
return head;
}
for(int i = 0;i<point;i++)
{
if(!cur){
printf("ERROR!");
}
pre=cur;
cur=cur->next;
}
node *in = creat_node(value);
pre->next=in;
in->next=cur;
return head;
}
node* back_insert_node(node *head,int value)//在尾部插入
{
node *cur = head;
node *new_ = creat_node(value);
while(cur->next){
cur=cur->next;
}
cur->next=new_;
return head;
}
node* delect_aim_node(node *head,int aim)//删除目标元素
{
if(!Yes_node(head)){
printf("ERROR");
return head;
}
node *pre,*cur=head;
while(cur){
if(cur->value==aim){
if(cur==head){
head=cur->next;
return head;
}
pre->next=cur->next;
printf("find and delete%d!\n",aim);
return head;
}
pre=cur;
cur=cur->next;
}
printf("did't find%d",aim);
return head;
}
void node_print(node *head)//打印出链表的所有元素
{
if(!Yes_node(head)){
printf("ERROR");
return;
}
node *cur=head;
while(cur){
printf("%d ",cur->value);
cur=cur->next;
}
printf("\n");
}
node* reverse_node(node *head)//反转链表
{
if(!Yes_node(head)){
printf("ERROR");
return head;
}
node *cur,*nex,*pre;
cur=head->next,nex,pre=head;
while(nex){
nex=cur->next;
cur->next=pre;
pre=cur;
cur=nex;
}
head->next=NULL;
head=pre;
return head;
}
int main()
{
int n;cin>>n;//需要插入值的个数
node *head=NULL;
while(n--)
{
int num;cin>>num;
if(head==NULL){
head=creat_node(num);
}else{
node *p=creat_node(num);
node *cur=head;
while(cur->next){
cur=cur->next;
}
cur->next=p;
}
}
int num=0,point,value;
printf("1:删除\n");
printf("2:插入\n");
printf("3:头插\n");
printf("4:尾插\n");
printf("5:反转链表\n");
printf("6:打印\n");
printf("其他任意值:退出\n");
while(1)
{
cin>>num;
switch(num){
case 1:
printf("输入需要删除的值:\n");
int aim;cin>>aim;
head = delect_aim_node(head,aim);
node_print(head);
break;
case 2:
printf("请输入要插入的位置(从零开始)和值:\n");
point,value;cin>>point>>value;
head = insert_node(head,value,point);
node_print(head);
break;
case 3:
printf("请输入要插入的值:\n");
value;cin>>value;
head = front_insert_node(head,value);
node_print(head);
break;
case 4:
printf("请输入要插入的值:\n");
value;cin>>value;
head = back_insert_node(head,value);
node_print(head);
break;
case 5:
head = reverse_node(head);
node_print(head);
break;
case 6:
node_print(head);
break;
default:
return 0;
}
}
}