逆序输出链表

题目:

输入一个链表的头结点,从尾到头反过来输出每个结点的值。


思路一:直接翻转链表

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值