有三种方法:
第一种:采用设置一个标志结点的的方法。
先将标志放在NULL,遍历链表如果cur->next==flag,那么就将cur->data打印出来,然后将标志前移,再次遍历就可以打印倒数第二个数据,然后再将标志前移,知道标志,在头结点plist位置
第二种:采用递归将其打印出来
但三种:采用栈的思想。
因为栈是先进后出,这刚好与这道题的思想一样,最先的最后打印,那么就可以用栈来进行编写了
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef int DataType;
typedef struct Linklist
{
DataType data;
struct Linklist* next;
}Node, *pNode, List, *pList;
void Init(pList* pplist)
{
assert(pplist != NULL);
*pplist = NULL;
}
pNode BuyNode(DataType d)
{
pNode newNode = NULL;
newNode = (pNode)malloc(sizeof(Node));
newNode->data = d;
newNode->next = NULL;
return newNode;
}
void PushFront(pList* pplist, DataType d)
{
pNode newNode = NULL;
assert(pplist != NULL);
newNode = BuyNode(d);
newNode->next = *pplist;
*pplist = newNode;
}
void Print(pList plist)
{
if (plist == NULL)
{
return;
}
else
{
while (plist != NULL)
{
printf("%d-->", plist->data);
plist = plist->next;
}
}
printf("over\n");
}
//采用栈的方法打印
void PrintTailToHeadStack(pList plist)
{
int stack[100] = { 0 };
int top = 0;
int i = 0;
pNode cur = plist;
while (cur != NULL)
{
stack[top++] = cur->data;
cur = cur->next;
}
top--;
while (top >= 0)
{
printf("%d-->", stack[top--]);
}
printf("over\n");
}
//采用递归的方法打印
void PtintTailToHeadRecursion(pList plist)
{
if (plist == NULL)
{
return;
}
else
{
PtintTailToHeadRecursion(plist->next);
}
printf("%d\n", plist->data);
}
//采用标志的方法打印
void PrintTailToHead(pList plist)
{
pNode flag = NULL;
while (flag != plist)
{
pNode cur = plist;
while (cur->next != flag)
{
cur = cur->next;
}
printf("%d-->", cur->data);
flag = cur;
}
printf("over\n");
}
void Test()
{
pList plist = NULL;
Init(&plist);
PushFront(&plist, 1);
PushFront(&plist, 2);
PushFront(&plist, 3);
PushFront(&plist, 4);
PrintTailToHead(plist);
PtintTailToHeadRecursion(plist);
PrintTailToHeadStack(plist);
Print(plist);
}
int main()
{
Test();
return 0;
}