遍历链表

来源:互联网 发布:好用的急救面膜知乎 编辑:程序博客网 时间:2024/06/05 21:10

问题:

问题链接:点击打开链接

题目描述:

建立一个升序链表并遍历输出。

输入:

输入的每个案例中第一行包括1个整数:n(1<=n<=1000),接下来的一行包括n个整数。

输出:

可能有多组测试数据,对于每组数据,
将n个整数建立升序链表,之后遍历链表并输出。

样例输入:
43 5 7 9
样例输出:
3 5 7 9
来源:
2000年华中科技大学计算机研究生机试真题

分析:

关键是单链表的一些操作。注意malloc之后对空间进行释放。
代码:

#include <iostream>#include<malloc.h>#define MAX 1010/* run this program using the console pauser or add your own getch, system("pause") or input loop */struct LNode{int data;LNode *next;};typedef struct LNode * LinkList;int initlist_l(LinkList &l){if((l = (LNode *)malloc(sizeof(LNode)) )== NULL){return 0;}l->next = NULL;return (1);}void insert(LinkList l,int x){//升序的 在单链表中插入一个结点xLNode *d = (LNode *)malloc(sizeof(LNode));d->data=x;d->next=NULL; LinkList q = l;LinkList p = q->next;//寻找x的位置while(p && p->data<x){q = p;p = p->next;} //将x插入到p的位置之前d->next = p;q->next = d; }void display(LinkList l){while(l->next){l = l->next;printf("%d ",l->data);}printf("\n");}int main(int argc, char** argv) {int n;while(scanf("%d",&n)!=EOF){LinkList l;    initlist_l(l);while(n--){int tmp;scanf("%d",&tmp);insert(l,tmp);}display(l);free(l);}return 0;}