链表
来源:互联网 发布:商品数据分析工作内容 编辑:程序博客网 时间:2024/06/03 19:42
链表学习
一些学习中的探索
输入n,表示要输入n个数,输入n个数,建链表,用链表的方法输出n个数顺序输出#include<stdio.h>#include<stdlib.h>void prn(struct node *head);struct node{ int data; struct node *next; }; struct node *p,*head;int main(){ int n; while(scanf("%d",&n)!=EOF) { head=NULL;//这种head是一直等于链表的第一个元素而不是作为一个标志指针指向第一个元素 while(n--) { //强转 p=(struct node *)malloc(sizeof(struct node)); scanf("%d",&p->data); p->next=head; head=p; //头插法 } //链表已经建好 prn(head); //用递归函数输出链表 } return 0;}void prn(struct node *head){ if(head==NULL) { return ; } prn(head->next); //用小秘书取找更小的秘书 printf("%d ",head->data); //逆着链表输出}逆序输出:#include<stdio.h>#include<stdlib.h>struct node{ int data; struct node *next;}*head,*p; //注意head是指针void prn(struct node *head){ while(head) { printf("%d ",head -> data); head = head -> next; }}int main(){ int n; scanf("%d",&n); head = NULL; while(n--) { p=(struct node *)malloc(sizeof(struct node)); scanf("%d",&p->data); p->next = head; head = p; } prn(head); return 0;}改良版:#include<stdio.h>#include<stdlib.h>struct node{ int data; struct node * next;}*head,*p;void input(int n){ int i; for(i = 0; i < n; i++) { p = (struct node *)malloc(sizeof(struct node)); scanf("%d",&p -> data); p -> next = head; head = p; }}void order_output(struct node *head){ if(head == NULL) return ; order_output(head -> next); //用递归来顺序输出 printf("%d ",head -> data);}void reverse_output(struct node *head){ while(head) { printf("%d ",head -> data); head = head -> next; }}int main(){ int n; head = NULL; scanf("%d",&n); input(n); printf("\n"); order_output(head); printf("\n"); reverse_output(head); return 0;}
0 0
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- MySQL索引背后的数据结构及算法原理
- 【Android】安卓学习笔记之ListView 的点击事件
- Poj 1961 Period
- 单片机轻松入门之三:蜂鸣器
- hrbust 哈理工oj 1570 田忌赛马【贪心】
- 链表
- 基于STM32红外计数的灯光照明
- Android开发之Service学习笔记
- MySql数据库的简介
- 强大的oracle函数wm_concat
- 一份面试题的总结 2
- 【POJ】2031 - Building a Space Station(克鲁斯塔尔)
- Android本地数据安全尝试(上)——SQLCipher
- argc 和 argv 经典实例 --写的真好