//链表和函数指针
//data域与指针域
//分类 分为动态链表和静态链表 分为带头和不带头 双向链表 循环链表
//结构体套结构体
#define _CRT_SECURE_NO_WARNINGS
#include<string>
#include<stdio.h>
#include<stdlib.h>
typedef struct A
{
int a;
int b;
char *p;
} A;
typedef struct B
{
int a;
A *p1;//结构体可以嵌套另外一个结构体的任何类型变量
//struct B tem1;//本结构体的类型大小无法确定,类型本质;固体大小内存块别名(不可以)
//struct B *p1;//可以,因为指针的内存大小固定了 指针变量的空间能确定
} B;
typedef struct stu
{
int id;
char name[100];
struct stu *next;
}stu;
int main1(void)
{
//静态链表
stu s1 = {0,"mike",NULL};
stu s2 = { 0, "like", NULL };
stu s3 = { 0, "love", NULL };
s1.next = &s2;
s2.next = &s3;
s3.next = NULL;//指针指向谁,就把谁的地址给它
//
stu *p = &s1;
while (p != NULL)
{
printf("id=%d name=%s",p->id,p->name);
p = p->next;
}
system("pause");
return 0;
}
typedef struct Node
{
int id;
struct Node *next;
}Node;
Node *SListCreat()
{
Node *head = NULL; //头节点作为标志 不保存数据
head = (Node *)malloc(sizeof(Node));
head->id = -1;
head->next = NULL;
Node *pCur = head;
Node *pNew = NULL;
int data ;
while (1)
{
printf("请输入数据");
scanf("%d", &data);
if (data==-1)//输入为1 退出
{
break;
}
pNew = (Node *)malloc(sizeof(Node));
pNew->id = data;
pNew->next = NULL;
pCur->next = pNew;
pCur = pNew;
}
return head;
}
int SListPrint(Node *head)
{
Node *pCur = head->next;
while (pCur!=NULL)
{
printf("%d->", pCur->id);
pCur = pCur->next;
}
printf("\n");
return 0;
}
int SListNodeInsert(Node *head,int x,int y)
{
if (head == NULL)
{
return -1;
}
Node *pPre = head;
Node *pCur = head->next;
while (pCur!=NULL)
{
if (pCur->id==x)
{
break;
}
pPre = pCur;
pCur = pCur->next;//指向下一个节点
}
//pcur为匹配点
Node *pNew = (Node*)malloc(sizeof(Node));
pNew->id = y;
pNew->next = NULL;
pPre->next = pNew;
pNew->next = pCur;
return 0;
}
int SList_delNode(Node *head,int x)
{
if (head == NULL)
{
return -1;
}
Node *pPre = head;
Node *pCur = head->next;
int flag = 0;
while (pCur != NULL)
{
if (pCur->id == x)
{
pPre->next = pCur->next;
free(pCur);
pCur = NULL;
flag = 1;
break;
}
pPre = pCur;
pCur = pCur->next;//指向下一个节点
}
if (flag==0)
{
printf("没有%d的值",x);
return -1;
}
return 0;
}
int SListNodeclear(Node *head)
{
int i = 0;
Node *tem = NULL;
while (head!=NULL)
{
tem = head->next;
free(head);
head = NULL;
head = tem;
i++;
}
return i;
}
int main(void)
{
Node*head=NULL;
head = SListCreat();//生成一个id数不一样的动态链表
SListPrint(head);//打印动态链表
SListNodeInsert(head,3,5);//在id为3的链表前插入一个id为5的链表
SListPrint(head);
SList_delNode(head,3);//删除id为3的节点
SListPrint(head);
int i=SListNodeclear(head);//删除所有的节点;
printf("%d",i);
system("pause");
return 0;
}