实现:链表查找,指定前后插入数据,改变数据
代码:
#include <stdio.h>
#include <stdlib.h>
//定义链表结构体
struct node
{
int data;
struct node *next;
};
//打印遍历链表表
void printnode(struct node *head)//定义头链表
{
while(head!=NULL){
if(head!=NULL){
printf("%d ",head->data);
head=head->next;
}
}
putchar('\n');
}
//统计链表节点个数
int NumNodes(struct node *head)
{
int num=0;
while(head != NULL){
num++;
head=head->next;
}
printf("共有链表节点%d\n",num);
return num;
}
//查找目标链表
int FindNode(struct node *head,int data)
{
int YesOrNot=0;
puts("请输入要查找的数据");
scanf("%d",&data);
getchar();
while(head != NULL){
if(head->data == data){
YesOrNot= 1;
}
head=head->next;
}
switch(YesOrNot){
case 1:
puts("找到了");
break;
case 0:
puts("没有");
break;
}
}
//指定后插
int InsertBhend(struct node *head,int data,struct node *new)
{
puts("请输入要插入在?数据后");
scanf("%d",&data);
getchar();
while(head != NULL){
if(head->data == data){
new->next = head->next;//找到目标节点,让新节点的next等于目前目标的位置
head->next=new;//改变目标节点的位置,后移
}
head=head->next;
}
}
//指定前插入
struct node *InsertFront(struct node *head,int data,struct node *new2)
{
struct node *phead=head;
puts("请输入要插入在?数据前");
scanf("%d",&data);
getchar();
if(head->data == data){//判断是不是要插入在第一个结点前
new2->next = head;
return new2;//是返回new2,不是head,且目前只能插在第一个节点。返回的new2为头的链表
}else{
while(phead!= NULL){
if(phead->next->data == data){//跳过第一个结点
new2->next = phead->next;//找到目标节点,让新节点的next等于目前目标的位置
phead->next=new2;//改变目标节点的位置,后移
return head;//头没有改变,返回head
}
phead=phead->next;
}
}
//return head;
}
//在头前插入
struct node *InsertFromHead(struct node *head,struct node *new)
{
if(head == NULL){
head = new;
return head;
}else{
new->next=head;
head=new;
}
return head;
}
//改节点数据
void Changedata(struct node *head,int data,int newdata)
{
puts("请输入要变的数据");
scanf("%d",&data);
puts("请输入要改为多少");
scanf("%d",&newdata);
getchar();
while(head != NULL){
if(head->data == data){
head->data = newdata;
}
head=head->next;
}
}
//主函数
int main()
{
int data=0;
int newdata=0;
struct node *head=NULL;
struct node *newhead=NULL;
struct node *head2=NULL;
struct node n1={1,NULL};
struct node n2={2,NULL};
struct node n3={3,NULL};
struct node n4={4,NULL};
struct node n5={5,NULL};
struct node new={100,NULL};
struct node new2={200,NULL};
n1.next=&n2;//结构体要指向结构体,不能写n2.data,指向不一样
n2.next=&n3;
n3.next=&n4;
n4.next=&n5;
printnode(&n1);
NumNodes(&n1);
FindNode(&n1,data);
InsertBhend(&n1,data,&new);
printnode(&n1);//打印的n1
head=InsertFront(&n1,data,&new2);
printnode(head);
Changedata(&n1,data,newdata);
printnode(head);
head=InsertFromHead(&n1,newhead);
printnode(head);
return 0;
}
结果: