描述
构造有序(升序)的单链表
并实现单链表的逆置
(可以采用结构化的程序设计方法实现,即不必定义类)
输入
输入链表中的数据。(用0表示输入的结束,0不能添加到链表中)
输出
按顺序输出有序链表中的数据
样例输入
4 1 6 8 2 0
样例输出
1 2 4 6 8 8 6 4 2 1
这里用的构造升序链表的方法有点无脑,不知道 有没有什么高级的数据结构可以实现升序单链表
采用了头插法实现单链表的逆置,如果有时间我再详细总结单链表逆置的几种方案
#include <iostream>
#include <algorithm>
using namespace std;
struct Node{int data;Node *next;
};
int a[100010];
int main()
{Node *first,*r,*s=NULL;first=new Node;int n;r=first;int i=0;while(cin>>n&&n){a[i++]=n;}sort(a,a+i);i=0;while(a[i]){s=new Node;s->data=a[i];r->next=s;r=s;i++;}r->next=NULL;r=first;while(r->next!=NULL){r=r->next;cout<<r->data<<" ";}cout<<endl;Node *p,*q;//q为的后继防止断链p=first->next;first->next=NULL;while(p!=NULL){q=p->next;p->next=first->next;first->next=p;p=q;}r=first;while(r->next!=NULL){r=r->next;cout<<r->data<<" ";}return 0;
}