首先输入链表中的结点个数,按照升序依次输入结点。最后,将链表按照逆序输出。
比如输入:
5 \链表中有5个结点
1 2 3 4 5 \依次输入5个结点的数值
5 4 3 2 1 \逆序输出5个结点
输入输出样例:1组
#1
样例输入:
5
1 2 3 4 5
样例输出:
5 4 3 2 1
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef struct tagListNode{
int data;
struct tagListNode* next;
}LNode, *LinkList;
void PrintList(LinkList head);
LinkList ReverseList(LinkList head);
int main()
{
LNode *head;
head = (LNode*)malloc(sizeof(LNode));
head->next = NULL;
head->data = -1;
LNode *p, *q;
p = head;
int n;
//cout<<"请输入节点个数";
cin>>n;
for(int i = 1; i <= n; i++)
{
int x;
cin>>x;
q = (LNode *)malloc(sizeof(LNode));
q->data = x;
q->next = NULL;
p->next = q;
p = q;
}
head = ReverseList(head);
PrintList(head);
return 0;
}
LinkList ReverseList(LinkList head)
{
if(head->next == NULL || head->next->next == NULL)
{
return head;
}
/* LNode* p = head->next;
int arr[256];
while(p != NULL)
{
int j=0;
arr[j++]=p->data;
p = p->next;
}
//LinkList L=NULL;
LinkList L=NULL;
LNode *s;
//int n=sizeof(arr)
for(int i=0;i<sizeof(arr);i++)
{
while(arr[i]!=-1)
{
s=(LNode *)malloc(sizeof(LNode));
s->data=arr[i];
s->next=L;
L=s;
}
}
return L;*/
LNode *t = NULL,
*p = head->next,
*q = head->next->next;
while(q != NULL)
{
t = q->next;
q->next = p;
p = q;
q = t;
}
head->next->next = NULL;/*设置链表尾*/
head->next = p; /* 调整链表头*/
return head;
}
void PrintList(LinkList head)
{
LNode* p = head->next;
while(p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
printf(" ");
}
/*#include <iostream>
#include<stdlib.h>
using namespace std;
typedef struct Incode
{
int data;
struct Incode *next;
}LNode,*LinkList;
LinkList Creat_LinkList1(double x)
{
LinkList L=NULL;
LNode *s;
while(x)
{
s=(LNode *)malloc(sizeof(LNode));
s->data=x;
s->next=L;
L=s;
}
return L;
}
LinkList Creat_LinkList2(double x)
{
LinkList L=NULL;
LNode *s,*r=NULL;
while(x!=-1);
{
s=(LNode *)malloc(sizeof(LNode));
s->data=x;
if(L==NULL)L=s;
else r->next=s;
r=s;
}
if(r!=NULL) r->next=NULL;
return L;
}
int main()
{
int n;
cin>>n;
int l1[256];
for(int i=0;i<n;i++)
{
int x;
cin>>x;
//l1=(LNode *)malloc(sizeof(LNode));
LinkList L1=Creat_LinkList2(x);
l1[i]=L1->data;
L1=L1->next;
}
int l2[256];
for(int j=0;j<n;j++)
{
int x;
x=l1[j];
LinkList L2=Creat_LinkList1(x);
l2[j]=L2->data;
L2=L2->next;
}
for(int k=0;k<n;k++)
{
cout<<l2[k]<<" ";
}
return 0;
}*/