本题目要求读入一系列整数,依次插入到双向循环链表的头部和尾部,然后顺序和逆序输出链表。
链表节点类型可以定义为
typedef int DataType;
typedef struct LinkedNode{
DataType data;
struct LinkedNode *prev;
struct LinkedNode *next;
}LinkedNode;
链表类型可以定义为
typedef struct LinkedList{
int length; /* 链表的长度 */
LinkedNode head; /* 双向循环链表的头节点 */
}LinkedList;
初始化链表的函数可声明为
void init_list(LinkedList *list);
分配节点的函数可声明为
LinkedNode *alloc_node(DataType data);
头部插入的函数可声明为
void push_front(LinkedList *list, DataType data);
尾部插入的函数可声明为
void push_back(LinkedList *list, DataType data);
顺序遍历的函数可声明为
void traverse(LinkedList *list);
逆序遍历的函数可声明为
void traverse_back(LinkedList *list);
输入格式:
输入一行整数(空格分隔),以-1结束。
输出格式:
第一行输出链表顺序遍历的结果,第二行输出逆序遍历的结果。
输入样例:
在这里给出一组输入。例如:
1 2 3 4 5 6 -1
输出样例:
5 3 1 2 4 6
6 4 2 1 3 5
链表式代码
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
#include <queue>
#include <map>
#include <set>
//#include <bits/stdc++.h>
using namespace std;
//#define int long long
typedef long long ll;
#define mem(a, b) memset(a, b, sizeof(a))
#define PI acos(-1)
#define LLu unsigned long long
#define PLL pair<ll, ll>
#define PII pair<int, int>
#define xx first
#define yy second
#define endl '\n'
#define O_O ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int gcd(int a, int b) {return b ? gcd(b, a%b) : a; }
int lcm(int a, int b) {return a/gcd(a, b)*b;}
const int N = 1e6 + 10, INF = 0x3f3f3f3f, mod = 1e9 + 7;
const double eps = 1e-6;
struct node
{
int data;
node *next;
node *pre;
};
int main()
{
node *head, *tail, *tt, *p;
head = new node;
tail = new node;
tt = new node;
head -> next = NULL;
head -> pre = NULL;
tail = head;
tt = head;
int x, cnt = 0, n = 0;
while(cin >> x && x != -1)
{
n ++;
p = new node;
p -> next = NULL;
p -> pre = NULL;
p -> data = x;
cnt ++;
if(cnt & 1)
{
tail -> pre = p;
p -> next = tail;
tail = p;
}
else
{
tt -> next = p;
p -> pre = tt;
tt = p;
}
}
int m = n;
while(tail && m)
{
if(tail == head)
{
tail = tail -> next;
continue;
}
m --;
if(m)
cout << tail -> data << " ";
else cout << tail -> data << endl;
tail = tail -> next;
}
m = n;
while(tt && m)
{
if(tt == head)
{
tt = tt -> pre;
continue;
}
m --;
if(m)
cout << tt -> data << " ";
else cout << tt -> data << endl;
tt = tt -> pre;
}
return 0;
}