本篇目的:先構建一個靜態鏈表,給大家以直觀印象。引誘你“愛”上鍊表。
本篇構建的鏈表不帶頭結點,第一個結點就是數據結點。
一、單鏈表的形態
二、單鏈表結點的C語言表示
struct node
{
int data;
struct node *next;
};
三、靜態結點
#include<stdio.h>
struct node
{
int data;
struct node *next;
};
int main()
{
struct node *head, a,b,c,d,e;
}
head爲指針變量,a、b、c、d、e爲五個靜態結點。
四、爲靜態結點賦值
head=0;//空指針
a.data=5;a.next=0;
b.data=8;b.next=0;
c.data=1;c.next=0;
d.data=2;d.next=0;
e.data=11;e.next=0;
五、靜態結點鏈起來
head=&a;
a.next=&b;
b.next=&c;
c.next=&d;
d.next=&e;
六、靜態鏈表遍歷
寫成函數形式:
void print_link_list(struct node *head)
{/*//head指向的就是數據,不帶頭結點 **/
struct node *p=head;
while(p!=0)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
七、完整程序
#include<stdio.h>
struct node
{
int data;
struct node *next;
};
void print_link_list(struct node *head)
{/*//head指向的就是數據,不帶頭結點 **/
struct node *p=head;
while(p!=0)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
int main(void)
{
struct node *head, a,b,c,d,e;
head=0;//空指針
a.data=5;a.next=0;
b.data=8;b.next=0;
c.data=1;c.next=0;
d.data=2;d.next=0;
e.data=11;e.next=0;
head=&a;
a.next=&b;
b.next=&c;
c.next=&d;
d.next=&e;
print_link_list(head);
return 0;
}
程序運行結果: