构造有序的单链表与逆置操作

构造有序(升序)的单链表

并实现单链表的逆置

(可以采用结构化的程序设计方法实现,即不必定义类)

输入输入链表中的数据。(用0表示输入的结束,0不能添加到链表中)输出按顺序输出有序链表中的数据样例输入

4 1 6 8 2 0

样例输出

1 2 4 6 8
8 6 4 2 1

数据结构版:

#include<iostream>
using namespace std;
struct Node
{
  int data;
  Node *next;
};
struct LinkList
{
public:
  LinkList();
  void Insert(int n);
  void reList();
  void printList();
private:
  Node *p, *s, *first,*r;
};

LinkList::LinkList()
{
  first = new Node;
  first->next = NULL;
}

void LinkList::Insert(int n)
{
  Node *front;
  s = new Node;
  s->data = n;
  front = first;
  p = first->next;
  while (p && n>p->data)
  {
    front = p;
    p = p->next;
  }
  s->next = p;
  front->next = s;
  return;
}

void LinkList::reList()
{
  p = first->next;
  first->next = NULL;
  while (p)
  {
    s = p->next;
    p->next = first->next;
    first->next = p;
    p = s;
  }
}

void LinkList::printList()
{
  p = first->next;
  while (p)
  {
    printf("%d ", p->data);
    p = p->next;
    
  }
  cout << endl;
}

int main()
{
  int n = 0;
  LinkList myList;
  while (cin>>n && n)
  {
    myList.Insert(n);
  }
  myList.printList();
  myList.reList();
  myList.printList();
}

骚操作版:

#include <iostream>
#include <set>
using namespace std;
set<int> se;
int main()
{
  int n = 0;
  while (cin >> n && n) se.insert(n);
  for (auto i : se) cout << i << " ";
  cout << endl;
  set<int>::iterator i = se.end(), j = se.begin();
  for (i--, j--; i != j; i--) cout << *i << " ";
}

 

 

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注

18 − 6 =