1 改变链表结构
即改变链表的指向,把所有的指向都反过来,再输出。
2 不改变链表结构
每遍历一个节点,就把节点的数据放入一个栈里。先进后出的思想。由此想到递归的思想,使用递归来处理。但递归的方法不是很好,当一个链表很长很长时,函数递归的层次很深,势必会导致栈溢出。这里为了举例我就用递归写,代码会很简单,毕竟上万个节点的链表也不会常有。也没必要存那么长,真有那么长的数据用数组加链表的组合来存会更好。
//输入一个链表的头结点,从尾到头输出
#include <iostream>
using namespace std;
struct node
{
int m_t;
struct node *next;
};
void func1()
{
struct node Top;
struct node *p = &Top;
struct node *tmp = p;
for(int i = 0; i < 10; i++)
{
tmp->next = new struct node;
tmp = tmp->next;
tmp->m_t = i;
}
tmp->next = NULL;
p = p->next;
while(p != NULL)
{
cout << p->m_t << " ";
p = p->next;
}
cout << endl;
struct node *p1 = &Top;
struct node *p2 = p1->next;
struct node *p3 = p2->next;
while(p2 != NULL)
{
p2->next = p1;
p1 = p2;
p2 = p3;
if(p3 != NULL)
p3 = p3->next;
}
Top.next = NULL;
while(p1->next != NULL)
{
cout << p1->m_t << " ";
p1 = p1->next;
}
cout << endl;
}
void myfunc(struct node *p)
{
if(p != NULL)
{
myfunc(p->next);
cout<< p->m_t << " ";
}
}
void func2()
{
struct node Top;
struct node *p = &Top;
struct node *tmp = p;
for(int i = 0; i < 10; i++)
{
tmp->next = new struct node;
tmp = tmp->next;
tmp->m_t = i;
}
tmp->next = NULL;
p = p->next;
myfunc(p);
cout << endl;
}
int main()
{
func1();//改变了链表的指向
func2();//不改变链表的指向 使用递归
return 0;
}