题目描述
建立一个升序链表并遍历反转输出。
输入描述:
输入的每个案例中第一行包括1个整数:n(1<=n<=1000),接下来的一行包括n个整数。
输出描述:
可能有多组测试数据,对于每组数据, 将n个整数建立升序链表,之后遍历链表并输出。
解题思路:
#include <cstdio>
#include <climits>
#include<iostream>
using namespace std;
struct node
{
int data;
node *next;
node(int n) : data(n), next(NULL) {};//结构体中方法初始化
};
void insert(node *&head, int num)
{
node *pre_p = head;
node *p = pre_p->next;
while (p)
{
if (p->data > num)
{
break;
}
p = p->next;
pre_p = pre_p->next;
}
pre_p->next = new node(num);
if (p != NULL)
{
pre_p->next->next = p;
}
}
void print_list(node *&head)
{
node *p = head->next;//本身含有头结点
while (true)
{
printf("%d ", p->data);
p = p->next;
if (p==NULL||p->next == NULL)//p=NULL是为了防止只有一个节点
{
break;
}
}
printf("%d\n", p->data);
}
void del_list(node *&head)
{
node *p = head;
while (p)
{
node *t = p;
p = p->next;
delete t;
}
}
void reverse2(node *head,node *p)//递归
{
if(p==NULL)
return ;
if(p->next==NULL)
{
head->next=p;
return;
}
reverse2(head,p->next);
// printf("%d\n",p->data);
p->next->next=p;
p->next=NULL;
}
void reverse(node *head)//非递归
{
node *current,*tmp;
current=head->next;
if(current!=NULL)
{
tmp=current;;
current=current->next;
tmp->next=NULL;
}
while(current!=NULL)
{
tmp=current;
current=current->next;
tmp->next=head->next;
head->next=tmp;
}
}
int main()
{
int n, num;
node *head;
while (scanf("%d", &n) != EOF)
{
head = new node(INT_MIN);
for (int i = 0; i < n; i++)
{
scanf("%d", &num);
insert(head, num);
}
print_list(head);//
printf("非递归反转\n");
reverse(head);
print_list(head);//反转后
node *p=head->next;
reverse2(head,p);
printf("递归反转\n");
print_list(head);//反转后
del_list(head);
}
return 0;
}