2:构造有序的单链表
-
总时间限制:
- 10000ms 内存限制:
- 65535kB
-
描述
-
-
构造有序(升序)的单链表
并实现单链表的逆置
(可以采用结构化的程序设计方法实现,即不必定义类)
输入
-
- 输入链表中的数据。(用0表示输入的结束,0不能添加到链表中) 输出
- 按顺序输出有序链表中的数据 样例输入
-
4 1 6 8 2 0
样例输出
-
1 2 4 6 8
8 6 4 2 1
-
-
题目大意:
-
-
如题。
-
-
思路:
-
-
查找构造,注意函数参数,是用的引用。知道为什么吗?自行百度,或者问问老师~~我不告诉你。
-
-
感想:
-
-
stl里面也有链表,用起来应该比这个舒服,不,是肯定比这个舒服,但是毕竟自己写一遍会好一些吧~~
-
话说,逆置没想起来怎么写。。。
-
-
AC代码:
-
-
#include<iostream> using namespace std; struct list { int number; list *next; }; void setnum(list *&head,int a) { list *s,*q,*p; s=new list; s->next=NULL; s->number=a; if(head==NULL) { head=s; return; } if(s->number<head->number) { s->next=head; head=s; return; } for(q=head,p=head->next;p;q=p,p=p->next) { if(s->number<p->number) { q->next=s; s->next=p; return; } } q->next=s; return; } int main() { int a; while(cin>>a) {list *head; list *rhead; head=NULL; while(a) { setnum(head,a); cin>>a; } int arr[1005]; int num=0; arr[0]=head->number; num++; cout<<head->number; head=head->next; while(head) { arr[num++]=head->number; cout<<" "<<head->number; head=head->next; } cout<<endl; cout<<arr[num-1]; for(int i=num-2;i>=0;i--) cout<<" "<<arr[i]; cout<<endl; } }
-