首先我们先定义一个链表的结构体。
typedef int DataType;
typedef struct Node {
DataType data;
struct Node* next;
}*SLNode,SLnode; //定义链表的结构体
因为是带头节点的链表,所以我们先创建一个头节点head,创建后将head传入insert中去。
int main(void)
{
int n;
SLNode head;
head = (SLNode)malloc(sizeof(SLnode)); //头节点
printf("请输入要创建的点链表的个数:\n");
scanf_s("%d",&n); //创建个数
insert(head,n);
print(head);
}
我们使用头插法来创建单链表,其实就是每次在链表的头部进行插入,这样插入会让输入和输入的顺序相反,例如我们输入123,输入的是321。
void insert(SLNode head,int n) //使用头插法创建单链表
{
SLNode p;
int i;
int data;
head->next = NULL;
for (i = 0; i < n; i++)
{
p= (SLNode)malloc(sizeof(SLnode));
scanf_s("%d",&data);
p->data = data;
p->next = head->next;
head->next = p;
}
}
完整代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef int DataType;
typedef struct Node {
DataType data;
struct Node* next;
}*SLNode,SLnode; //定义链表的结构体
void insert(SLNode q,int n);
void print(SLNode head);
int main(void)
{
int n;
SLNode head;
head = (SLNode)malloc(sizeof(SLnode)); //头节点
printf("请输入要创建的点链表的个数:\n");
scanf_s("%d",&n); //创建个数
insert(head,n);
print(head);
}
void insert(SLNode head,int n) //使用头插法创建单链表
{
SLNode p;
int i;
int data;
head->next = NULL;
for (i = 0; i < n; i++)
{
p= (SLNode)malloc(sizeof(SLnode));
scanf_s("%d",&data);
p->data = data;
p->next = head->next;
head->next = p;
}
}
void print(SLNode head)
{
SLNode L = head->next;
while (L ->next != NULL)
{
printf("%-2d",L->data);
L = L->next;
}
printf("%-2d\n",L->data);
}
尾插法
尾插法和头插法的插法刚好相反,尾插法是从链表尾部开始插入,所以插入的顺序和输出的顺序是完全一致的。例如我们输入的顺序是 1 2 3,输出的就是 1 2 3。
void insert(SLNode head, int n) //尾插法的写法
{
SLNode q,p;
int n,data;
q = head;
for (int i; i < n; i++)
{
p = (SLNode)malloc(sizeof(SLnode));
scanf_s("%d",&data);
p->data = data;
p->next = q->next;
q->next = p;
q = p;
}
}
其余代码和上面的完整代码一样。
结果: