链表的个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域。
链表包括单向链表(也就是今天要写的),双向链表,循环链表;
在网上看了不上建链表,建树的代码,都是用C++,用函数是用到了引用,而我想用C语言写出来,就避不开指针了~~~恶补了一天的指针终于把链表和树写出来了,树的代码以后会写;
今天写的代码是按从小到大顺序建表的;
比如输入:5,2,6,4,3;
输出:2,3,4,5,6;
当然链表一般不需要按顺序建,我会在最后补一个无序的,用上边的例子输出就是:5,2,6,4,3;
好了,上代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct LinkedList{ //结构体用来储存链表每个节点的内容,包括该点的值,指向下一个的指针;
int data;
struct LinkedList *next;
};
//注意下面的链表按从小到大顺序建造;
void SetList(struct LinkedList **head, int val){ //链表的构造函数,传参为链表的头结点(因为要改变其值,所以传地址,指针的指针),增加的值val;
struct LinkedList *t; //定义一个新的结构体指针,用来存需要插入的点;
t=(struct LinkedList *)malloc(sizeof(struct LinkedList));
t->data=val;
t->next=NULL;
if(*head==NULL){ //if 头结点为空,直接给头结点赋值;
(*head)=t;
return;
}
if((*head)->data>val){ //if头结点大于新增点,将新增点设为头结点;
t->next=(*head);
(*head)=t;
return;
}
else{
if((*head)->next==NULL || (*head)->next->data>val)//if 头结点的next为空或头结点的next的值大于新增点,将新增点插入头结点后边;
{
t->next=(*head)->next;
(*head)->next=t;
return;
}
SetList(&((*head)->next), val);//从头结点开始向后找,直到插入新节结点,递归思想;
}
}
void ShowList(struct LinkedList *head){ //链表的打印;递归思想;
if(head==NULL){
printf("\n");
return;
}
printf("%d",head->data);
if(head->next!=NULL) printf(" ");
ShowList(head->next);
}
int main(){
int N;
scanf("%d",&N);// 输入链表的结点数;
struct LinkedList *head;
head=NULL; //设链表为空;
while(N--){
int val;
scanf("%d",&val);
SetList(&head, val);
}
ShowList(head);//打印链表;
return 0;
}
然后是无序链表的代码,就不详细注释了;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct ListNode{
int data;
struct ListNode *next;
} *list;
void SetLinkNode(struct ListNode **list, int val){ //建表函数;
struct ListNode *t;
t=(struct ListNode *)malloc(sizeof(struct ListNode));
t->data=val;
t->next=NULL;
if(*list==NULL){
(*list)=t;
return;
}
else SetLinkNode(&((*list)->next), val);
}
void ShowList(struct ListNode *list){ //打印函数;
if(list==NULL) return;
if(list->next==NULL) printf("%d\n",list->data);
else printf("%d ",list->data);
ShowList(list->next);
}
int main(){
int a;
int i;
list=NULL;
int N;
scanf("%d",&N);// 链表的结点数;
for(i=0; i<N; i++){
scanf("%d",&a);
SetLinkNode(&list, a);
}
ShowList(list);
return 0;
}