链表的插入主要有两种方式:头插法和尾插法
#include <stdio.h>
#include <stdlib.h>//经Visual C++6.0中查看,malloc函数在malloc.h或者stdlib.h里都有,不知道为何引用memory.h也可以编译通过,但是会有警告:warning C4013: 'malloc' undefined; assuming extern returning int
typedef struct Lnode{//回顾1:关于结构体的定义,有哪几种方法?
int num;
struct Lnode *next;
}Node,*pNode;
int main(){
int n;
pNode p,head,temp;//此处是头指针直接指向首结点
head=NULL;
printf("please input the number of lianbiao:\n");
scanf("%d",&n);
while(n){
printf("please input the %dth num:\n",n--);
temp=(pNode)malloc(sizeof(Node));
scanf("%d",&(temp->num));
if(head==NULL){
head=p=temp;
temp->next=NULL;
}
else{
p->next=temp;//尾插法请不要忘记将尾指针移动啊!
temp->next=NULL;
p=temp;
/* or头插法
temp->next=p;
head=temp;
*/
}
}
p=head;
while(p!=NULL){
printf("%d ",p->num);
p=p->next;
}
return 0;
}
回顾:结构体
1结构体的定义
struct [point] {//方括号内为结构标记,是可选的。
int x;
int y;
};
关键字struct 引入结构声明。结构声明由包含在花括号内的一系列声明组成。关键字struct后面的名字是可选的,称为结构标记(这里是point)。结构标记用于为结构命名,在定义之后,结构标记就代表花括号内的声明,可以用它作为该声明的简写形式。
2结构体声明
- 可以直接用struct{...} x,y,z来声明。
- 也可以定义了之后可以用 struct +结构标记 来声明变量,如:
struct point x,y,z;
本质上和int x,y,z;是类似的
3结构体赋值
- 直接赋值
struct point x={100,100};是可以的
也可以用结构运算符“.”赋值。即是 结构体名.成员名 如:
struct point hehe;
hehe.x=100;
hehe.y=100;
- 注意:结构体内部支持嵌套,如:
struct rect {
struct point pt1;
struct point pt2;
};
4结构体指针
可以用结构体指针加上->操作符取得结构体内部的元素。即是结构体指针->成员名;
结构体指针的赋值方法:取地址符&
struct point x;
struct point *p=&x;
备注:->和.运算符的优先级都高于自增操作符,所以 ++p->len将增加len 的值,而不是增加p 的值, 这是因为,其中的隐含括号关系是++(p->len)。
可以使用括号改变结合次序。例如:(++p)->len将先执行p的加1 操作,再对len执行操作;而(p++)->len则先对len执行操作,然后再将p加1(该表达式中的括号可以省略)。
同样的道理,*p->str 读取的是指针str 所指向的对象的值;*p->str++先读取指针str 指向的对象的值,然后再将str 加1(与*s++相同);(*p->str)++将指针str 指向的对象的值加1;*p++->str先读取指针str指向的对象的值,然后再将p加1。
5结构体数组
struct key {
char *word;
int count;
};
struct key keytab[NKEYS];
或者
struct key{
char *word;
int count;
} kaytab[NKEYS];
6使用typedef 类型定义符来定义结构体
typedef struct Lnode{
int num;
struct Lnode *next;//注意这里不能用类型定义符定义的Node和pNode
}Node,*pNode;
注意事项:
尽量先画图再写程序,应该将输入输出创建链表等分开成单独的子函数实现,便于后面的代码的重复使用,经过改写后如下:
#include <stdio.h>
#include <stdlib.h>
typedef struct Lnode{
int num;
struct Lnode *next;
}Node,*pNode;
pNode createLinkedList(int n){//用到的函数需在main前面声明
pNode temp,head,p; //需分别声明再赋值。
head=NULL;
while(n){
printf("please input the %dth num:\n",n--);
temp=(pNode)malloc(sizeof(Node));
scanf("%d",&(temp->num));
if(head==NULL){
head=p=temp;
temp->next=NULL;
}
else{
// p->next=temp;
// p=temp; //尾插法
temp->next=head;//头插法
head=temp;
}
}
return head;
}
void printLinkedList(pNode head){//打印链表函数
pNode p=head;
while(p!=NULL){
printf("%d ",p->num);
p=p->next;
}
return;
}
int main(){
int n;
pNode h=NULL;
printf("please input the number of lianbiao:\n");
scanf("%d",&n);
h=createLinkedList(n);
printLinkedList(h);
return 0;
}
参考资料:《C程序设计语言 第二版新版》
ps:无力吐槽CSDN这难用的编辑器。