题目:
输入一个链表的头结点,从尾到头反过来输出每个结点的值。
思路一:直接翻转链表
#include <stdio.h>
#include <stdlib.h>
#include <stack>
typedef int elem;
typedef struct node
{
elem data;
struct node *next;
}LNode, *LINKLIST;
/*翻转链表*/
void reverseLink(LINKLIST list)
{
LNode* pre = NULL;
LNode* node = list->next;
LNode* next;
LNode* head = NULL;
while (node != NULL)
{
next = node->next;
if (next == NULL)
{
head = node;
}
node->next = pre;
pre = node;
node = next;
}
list->next = head;
}
/*采用尾插法,创建单链表*/
void createList(LINKLIST list, elem data)
{
LNode* p = list;
LNode* newNode;
while (p->next != NULL)
{
p = p->next;
}
newNode = (LNode*)malloc(sizeof(LNode));
newNode->next = NULL;
newNode->data = data;
p->next = newNode;
}
/*打印单链表*/
void printList(LINKLIST list, void(*print)(elem))
{
LNode* p = list->next;
while (p != NULL)
{
print(p->data);
p = p->next;
}
printf("\n");
}
/*打印结点值*/
void printElem(elem data)
{
printf("%d\t", data);
}
int main()
{
LINKLIST list = NULL;
elem data[] = {1,2,3,4,5,6};
int i;
list = (LINKLIST)malloc(sizeof(LNode));
list->next = NULL;
list->data = 0;
for (i=0; i<6; i++)
{
createList(list, data[i]);
}
printList(list, printElem);
reverseLink(list);
printList(list, printElem);
return 0;
}
思路二:递归输出
#include <stdio.h>
#include <stdlib.h>
#include <stack>
typedef int elem;
typedef struct node
{
elem data;
struct node *next;
}LNode, *LINKLIST;
/*翻转链表*/
void reverseLink(LINKLIST list)
{
if (list == NULL)
{
return;
}
reverseLink(list->next);
if (list->next != NULL)
printf("%d\t", list->next->data);
}
/*采用尾插法,创建单链表*/
void createList(LINKLIST list, elem data)
{
LNode* p = list;
LNode* newNode;
while (p->next != NULL)
{
p = p->next;
}
newNode = (LNode*)malloc(sizeof(LNode));
newNode->next = NULL;
newNode->data = data;
p->next = newNode;
}
/*打印单链表*/
void printList(LINKLIST list, void(*print)(elem))
{
LNode* p = list->next;
while (p != NULL)
{
print(p->data);
p = p->next;
}
printf("\n");
}
/*打印结点值*/
void printElem(elem data)
{
printf("%d\t", data);
}
int main()
{
LINKLIST list = NULL;
elem data[] = {1,2,3,4,5,6};
int i;
list = (LINKLIST)malloc(sizeof(LNode));
list->next = NULL;
list->data = 0;
for (i=0; i<6; i++)
{
createList(list, data[i]);
}
printList(list, printElem);
reverseLink(list);
//printList(list, printElem);
return 0;
}