链表(一)
一、单链表创建:
链表结点如图:
可以使用结构体类型的变量来存储链表中的结点元素,每一个结点中存放地址的部分可用指针来实现,代码如下:
typedef struct node
{
int data;
struct node *next;
}node,*linklist;
//*linklist用于存放头节点,linklist等价node*
//linklist 结构体指针类型
1.尾插(将新的结点插入当前链表的尾结点之后,存储数据顺序与输入顺序一致)
图示:
代码实现:
r->next = s;//连接尾节点与新节点
r=s;//尾指针移向新的尾节点
循环结束后
r->next=NULL;
完整代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node,*linklist;
linklist creat_L();
void print(linklist L);
linklist creat_L()
{
node *s,*r;
linklist L;//头指针
L= (linklist)malloc(sizeof(node));//建立头节点
r=L;
L->next =NULL;
s=(node*)malloc(sizeof(node));
//printf("please input data(int)");
scanf("%d",&s->data);
while(s->data)
{
r->next = s;//连接尾节点与新节点
r=s;//尾指针移向新的尾节点
s=(node*)malloc(sizeof(node));
scanf("%d",&s->data);
}
r->next = NULL; //尾节点指针域为空
free(s);//释放未使用的节点
return L;
}
void print(linklist L)
{
node *p;
p = L-> next;
while(p)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
int main(void)
{
linklist L;
L = creat_L();
print(L);
}
2.头插(将新结点插入到当前链表的表头结点之后)
图示:
代码实现:
① s->next =L->next ;//新节点插入尾节点之前
② L->next =s;//新节点与头结点连接
完整代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node,*linklist;
linklist creat_L();
void print(linklist L);
linklist creat_L()
{
node *s;
linklist L;
L=(linklist)malloc(sizeof(node));
L->next = NULL;
s=(node*)malloc(sizeof(node));
scanf("%d",&s->data);
while( s->data )
{
s->next =L->next ;
L->next =s;
s=(node*)malloc(sizeof(node));
scanf("%d",&s->data);
}
free(s);
return L;
}
void print(linklist L)
{
node *p;
p = L-> next;
while(p)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
int main(void)
{
linklist L;
L = creat_L();
print(L);
}
3.应用:单链表的逆置
思路:首先尾插法建立单链表,然后使用头插遍历链表
图示:
代码实现:
void revl (linklist L)
{
node *p,*q;
p=L->next;//注意顺序,记录头节点后的第一个节点,记尾结点p
L->next=NULL;//断开连接,得到头节点
while(p)
{
q=p->next;//记录尾结点后下一个有数据的结点为q
p->next=L->next;//使用头插插入q
L->next=p;
p=q;//更新
}
}
完整代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node,*linklist;
linklist creat_L ();
void print (linklist L);
void revl (L);
linklist creat_L ()
{
node *s,*r;
linklist L;
L= (linklist)malloc(sizeof(node));
r=L;
L->next =NULL;
s=(node*)malloc(sizeof(node));
scanf("%d",&s->data);
while(s->data)//尾插
{
r->next = s;
r=s;
s=(node*)malloc(sizeof(node));
scanf("%d",&s->data);
}
r->next = NULL;
free(s);
return L;
}
void revl (linklist L)
{
node *p,*q;
p=L->next;//注意顺序,记录头节点后的第一个节点,记尾结点p
L->next=NULL;//断开连接,得到头节点
while(p)
{
q=p->next;//记录尾结点后下一个有数据的结点为q
p->next=L->next;//使用头插插入q
L->next=p;
p=q;//更新
}
}
void print (linklist L)
{
node *p;
p = L-> next;
while(p)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
int main (void)
{
linklist L;
L = creat_L ();
revl (L);
print (L);
}