数据结构
typedef struct LNode
{
int data;
int* next;
}LNode;
创建链表(头插法)
void CreateLlist(LNode**head)
{
*head = (LNode*)malloc(sizeof(LNode));
(*head)->next = NULL;
int n;
printf("请输入元素个数");
scanf_s("%d", &n);
int x;
LNode* p;
for (int i = 0;i < n;i++)
{
printf("请输入第%d个元素", i + 1);
scanf_s("%d", &x);
p = (LNode*)malloc(sizeof(LNode));
p->data = x;
p->next = (*head)->next;
(*head)->next = p;
}
}
传入一个*head指针;因为这个指针要改变所以用二级指针;
p是用来创建新节点的指针 ,头插是真的插进去了;
头插完整测试代码
#include<stdio.h>
#include<stdlib.h>
typedef struct LNode
{
int data;
int* next;
}LNode;
void CreateLlist(LNode**head)
{
*head = (LNode*)malloc(sizeof(LNode));
(*head)->next = NULL;
int n;
printf("请输入元素个数");
scanf_s("%d", &n);
int x;
LNode* p;
for (int i = 0;i < n;i++)
{
printf("请输入第%d个元素", i + 1);
scanf_s("%d", &x);
p = (LNode*)malloc(sizeof(LNode));
p->data = x;
p->next = (*head)->next;
(*head)->next = p;
}
}
void main()
{
LNode* head,*b;
CreateLlist(&head);
b = head->next;
while (b!=NULL)
{
printf("%d",b->data);
b = b->next;
}
}
因为考试是手写,不像上机,需要变量的时候在前面添就可以了,为了考试不漏;在此与自己做下约定;
先指针,再个数 再元素
尾插法
void Tailinsert(Lnode** head)
{
(*head) = (Lnode*)malloc(sizeof(Lnode));
(*head)->next = NULL;
Lnode* tail = *head;
int n;
printf("请输入元素个数");
scanf_s("%d", &n);
Lnode* NewNode;
int x;
for (int i = 0;i < n;i++)
{
printf("请输入第%d个元素\n",i+1);
scanf_s("%d",&x);
NewNode = (Lnode*)malloc(sizeof(NewNode));
NewNode->data = x;
NewNode->next = NULL;
tail->next = NewNode;
tail = NewNode;
}
}
这和后边的入队一样哈哈哈;它其实不算”插“更像是”排“;
尾插法完整测试代码
#include<stdio.h>
#include<stdlib.h>
typedef struct Lnode
{
int data;
int* next;
}Lnode;
void Tailinsert(Lnode** head)
{
(*head) = (Lnode*)malloc(sizeof(Lnode));
(*head)->next = NULL;
Lnode* tail = *head;
int n;
printf("请输入元素个数");
scanf_s("%d", &n);
Lnode* NewNode;
int x;
for (int i = 0;i < n;i++)
{
printf("请输入第%d个元素\n",i+1);
scanf_s("%d",&x);
NewNode = (Lnode*)malloc(sizeof(NewNode));
NewNode->data = x;
NewNode->next = NULL;
tail->next = NewNode;
tail = NewNode;
}
}
void main()
{
Lnode* head,*b;
Tailinsert(&head);
b = head->next;
while (b!=NULL)
{
printf("%d", b->data);
b=b->next;
}
}