您的位置:首页 > 职场人生

面试题5 从尾到头打印链表

2014-09-10 11:00 363 查看


方法一: 使用栈

[html] view
plaincopy

#include <stack>

#include <stdio.h>

typedef struct ListNode

{

int m_nValue;

ListNode *m_pNext;

}ListNode;

ListNode *createListNode(int value)

{

ListNode *node = new ListNode();

node->m_nValue = value;

node->m_pNext = NULL;

return node;

}

void connectListNode(ListNode *currentNode, ListNode *nextNode)

{

if(currentNode == NULL)

{

printf("error");

return;

}

currentNode->m_pNext = nextNode;

}

void destroyList(ListNode *head)

{

ListNode *node = head;

if(node)

{

head = head->m_pNext;

delete node;

node = head;

}

}

void printList(ListNode *head)

{

printf("原先列表:\n");

ListNode *node = head;

while(node)

{

printf("%d ", node->m_nValue);

node = node->m_pNext;

}

printf("\n");

}

void printListReversingly(ListNode *head)

{

std::stack<ListNode *> nodes;

ListNode *node = head;

while(node != NULL)

{

nodes.push(node);

node = node->m_pNext;

}

while(!nodes.empty())

{

node = nodes.top();

printf("%d ", node->m_nValue);

nodes.pop();

}

}

void main()

{

ListNode *node1 = createListNode(1);

ListNode *node2 = createListNode(2);

ListNode *node3 = createListNode(3);

ListNode *node4 = createListNode(4);

ListNode *node5 = createListNode(5);

connectListNode(node1, node2);

connectListNode(node2, node3);

connectListNode(node3, node4);

connectListNode(node4, node5);

printList(node1);

printf("从尾到头打印列表:\n");

printListReversingly(node1);

printf("\n");

destroyList(node1);

}

运行结果如下:



方法二: 递归

源程序

[cpp] view
plaincopy

#include <stdio.h>

#include <stdlib.h>

#include "stack.h"

//尾插法建立链表

void create_list(LinkList &L){

LinkList p,q;

int e;

L=(LinkList)malloc(sizeof(Node));

L->next=NULL;

q=L;

printf("建立链表以0结束\n");

scanf("%d",&e);

while(e)

{

p=(LinkList)malloc(sizeof(Node));

p->data=e;

p->next=NULL;

q->next=p;

q=p;

scanf("%d",&e);

}

}

//递归方法输出链表

void PrintReverse(LinkList &L)

{

if(L!=NULL)

{

if(L->next!=NULL)

{

PrintReverse(L->next);

printf("%d\t",L->next->data);

}

}

}

int main()

{

LinkList L,q;

int m;

create_list(L);

q=L;

LiStack S;

InitStack(S);

L=L->next;

printf("原链表:\n");

while(L)

{

Push(S,L->data);

printf("%d\t",L->data);

L=L->next;

}

printf("\n递归输出新链表:\n");

PrintReverse(q);

printf("\n栈链表:\n");

while(!StackEmpty(S))

{

Pop(S,m);

printf("%d\t",m);

}

return 0;

}

结果

[cpp] view
plaincopy

建立链表以0结束

1 2 3 4 0

原链表:

1 2 3 4

递归输出新链表:

4 3 2 1

栈链表:

4 3 2 1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: