链表小结
.需要先清楚一点,指针指向的是地址!!!
1.创建链表,插入数据
1.头插法(看图)
代码实现
#include<stdio.h> #include<stdlib.h> struct student { int data; struct student *next; }; int main() { int a[10]={1,2,3,4,5,6,7,8,9,10};/*无头节点-头插法*/ struct student *head=NULL,*p; for(int i=0;i<10;i++) { p=(struct student*)malloc(sizeof(struct student)); p->next=NULL; p-> data=a[i]; p->next=head;/*指针指向的是地址*/ head=p; } p=head;/*head不能带着一直跑会乱掉*/ while(p!=NULL) { printf("%d ",p->data); p=p->next; } return 0; }
#include<stdio.h> #include<stdlib.h> struct stu { int data; struct stu *next; }; int main() { int a[3]={1,2,3}; struct stu *List,*p;/*带头节点*/ List=(struct stu*)malloc(sizeof(struct stu)); List->next=NULL; for(int i=0;i<3;i++) { p=(struct stu*)malloc(sizeof(struct stu)); p->data=a[i]; p->next=List->next; List->next=p; } p=List->next;/*从第一个节点开始*/ while(p) { printf("%d",p->data); p=p->next; }return 0; }
2.尾插法
代码实现
#include<stdio.h> #include<stdlib.h> struct stu { int data; struct stu *next; }; int main() { int a[5]={1,2,3,4,5}; struct stu *head=NULL,*tail=NULL,*p; for(int i=0;i<5;i++) { p=(struct stu*)malloc(sizeof(struct stu)); p->data=a[i];p->next=NULL; if(head) {tail->next=p; }else { head=p;} tail=p; }p=head; while(p) { printf("%d ",p->data); p=p->next; }return 0; }
#include<stdio.h> #include<stdlib.h> struct stu { int data; struct stu *next; }; int main() { int a[3]={1,2,3}; struct stu *List,*tail=NULL,*p; List=(struct stu*)malloc(sizeof(struct stu)); List->next=NULL; tail=List; for(int i=0;i<3;i++) { p=(struct stu*)malloc(sizeof(struct stu)); p->data=a[i]; p->next=NULL; tail->next=p; tail=p; } p=List->next; while(p) { printf("%d ",p->data); p=p->next; }return 0; }
遍历链表
for(p=head;p!=NULL;p=p->next) { printf("%d",p->data); }
while(p) { printf("%d ",p->data); p=p->next; }
3.删除节点
if(q->data==2) { p->next=q->next; free(q); q=p->next; }else { p=p->next; q=p->next; }
先这样啦,如果有错误,欢迎指出( •̀ ω •́ )✧