关于数据逆序问题,当遇到这个问题是我们一般会想到两种解决办法:
1,使用栈先入后出(STL中的stack直接使用);
2.学习过二叉树的对与递归可能比较了解,而第二种就是递归。
下面我们就已链表的逆序输出,做一下展示。(在此我们没有必要将整个链表结构逆序)
#include <stdio.h>
#include <stdlib.h>
#include <stack>
struct node
{
int data;
struct node *next;
};
struct node *head; //创建头结点
void ListCreat() //创建链表
{
struct node *Node;
struct node *index;
int i = 0;
head = (struct node *)malloc( sizeof(struct node) ); //个人喜好每个链表有一个头结点
index = head;
while(i < 10)
{
Node = (struct node *)malloc(sizeof(struct node));
Node->data = i;
Node->next = NULL;
index->next = Node;
index = index->next;
i++;
}
}
//栈方法
void Listprint1(struct node *head)
{
struct node *ptr1 = NULL;
struct node *ptr = head;
std::stack<struct node *>Stack;
if(NULL==ptr)
return;
while(ptr->next != NULL) //入栈
{
Stack.push(ptr->next);
ptr= ptr->next;
}
while(!Stack.empty()) //出栈
{
ptr1= Stack.top();
printf("%d",ptr1->data);
Stack.pop();
}
}
//递归法
void Listprint2(struct node *head)
{
struct node *ptr = head->next;
if(NULL == ptr)
return;
Listprint2(ptr);
printf("%d",ptr->data);
}
void main()
{
struct node *index;
ListCreat();
index = head;
index = index->next;
while( index != NULL )
{
printf("%d\n ", index->data);
index = index->next;
}
printf("--------------------------------------\n");
//Listprint1(head);
Listprint2(head);
}
总结:以后不论是面试还是工作当中遇到此类问题是一般运用此两种方法。当然还会有其它方法在此希望大神指导。