尾插法
定义结构体
typedef int DataType;
typedef struct Node {
DataType data;
struct Node* next;
}*SLNode, SLnode; //定义链表的结构体
尾插法创建链表
void insert(SLNode head, int n)
{
SLNode q,p;
int i, data;
p = head;
scanf_s("%d",&data);
head->data = data;
head->next = NULL;
for (i = 0; i < n-1; i++)
{
q = (SLNode)malloc(sizeof(SLnode));
scanf_s("%d",&data);
q->data = data;
q->next = p->next;
p->next = q;
p = q;
}
}
注意因为是无头结点,所以这里的head不是头结点而是头指针。(头结点的数据域里面我们没有存放数据,头指针则是指向第一个存放数据的结构体。)
完整代码:
#include<stdio.h>
#include<stdlib.h>
typedef int DataType;
typedef struct Node {
DataType data;
struct Node* next;
}*SLNode, SLnode; //定义链表的结构体
void insert(SLNode head, int n);
void print(SLNode head);
int main(void)
{
SLNode head; // 注意这里的head不是头结点.
head = (SLNode)malloc(sizeof(SLnode));
int n;
printf("请输入要创建的链表的长度:");
scanf_s("%d", &n);
insert(head, n);
print(head);
return 0;
}
void print(SLNode head)
{
SLNode L ,q;
L = head;
int i=0;
while (L!=NULL)
{
printf("%-2d", L->data);
q = L;
L = L->next;
free(q);
}
}
void insert(SLNode head, int n)
{
SLNode q,p;
int i, data;
p = head;
scanf_s("%d",&data);
head->data = data;
head->next = NULL;
for (i = 0; i < n-1; i++)
{
q = (SLNode)malloc(sizeof(SLnode));
scanf_s("%d",&data);
q->data = data;
q->next = p->next;
p->next = q;
p = q;
}
}
运行结果:
头插法
注意在print子函数中不要直接传入head参数,这样输出的答案是错误的。因为子函数insert()没有返回head的值,所以主函数会认为head的值是没有改变的。例如我们输入 1 2 3,不会输出3 2 1,输出的是1,因为计算机会认为head指向的是1,而不是3.
SLNode insert(SLNode head, int n)
{
SLNode q;
int i, data;
q = head;
scanf_s("%d", &data);
q->data = data; // head->data=data;
q->next = NULL; // head->next=NULL
for (i = 0; i < n - 1; i++)
{
scanf_s("%d",&data);
q = (SLNode)malloc(sizeof(SLnode));
q->data = data;
q->next = head;
head = q;
}
return head;
}
完整代码:
#include<stdio.h>
#include<stdlib.h>
typedef int DataType;
typedef struct Node {
DataType data;
struct Node* next;
}*SLNode, SLnode; //定义链表的结构体
SLNode insert(SLNode head, int n);
void print(SLNode head);
int main(void)
{
SLNode head,m; // 注意这里的head不是头结点.
head = (SLNode)malloc(sizeof(SLnode));
int n;
printf("请输入要创建的链表的长度:");
scanf_s("%d", &n);
m=insert(head, n);
print(m);
return 0;
}SLNode insert(SLNode head, int n)
{
SLNode q;
int i, data;
q = head;
scanf_s("%d", &data);
q->data = data; // head->data=data;
q->next = NULL; // head->next=NULL
for (i = 0; i < n - 1; i++)
{
scanf_s("%d",&data);
q = (SLNode)malloc(sizeof(SLnode));
q->data = data;
q->next = head;
head = q;
}
return head;
}
void print(SLNode head)
{
while (head != NULL)
{
printf("%-2d",head->data);
head = head->next;
}
}