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

来源:互联网 发布:淘宝天猫京东入驻条件 编辑:程序博客网 时间:2024/06/10 01:49

题目:输入一个链表的头结点,从尾到头反过来打印每个节点的值。

代码示例(用栈也行):

#include<iostream>using namespace std;struct Node{int data;Node *next;};class LinkList{Node *head;public:LinkList();~LinkList();bool CreateList(int a[], int n);bool InsertListF(int data);void Disp(void);friend bool InverseList(const LinkList &src, LinkList &dst);};LinkList::LinkList(){head = new Node();head->next = NULL;}LinkList::~LinkList(){Node *p = head->next;Node *pre = head;while (p != NULL){delete pre;pre = p;p = p->next;}delete pre;}bool LinkList::CreateList(int a[], int n){if (n <= 0)return false;Node *pre = head;for (int i = 0; i < n; i++){Node *p = new Node();p->data = a[i];pre->next = p;pre = p;}pre->next = NULL;return true;}bool LinkList::InsertListF(int data){Node *p = new Node();p->data = data;p->next = head->next;head->next = p;return true;}void LinkList::Disp(){Node *p = head->next;while (p != NULL){cout << p->data << " ";p = p->next;}cout << endl;}bool InverseList(const LinkList &src, LinkList &dst){if (src.head->next == NULL)return false;Node *p = src.head->next;while (p != NULL){int temp = p->data;dst.InsertListF(temp);p = p->next;}}void main(){LinkList L1, L2;int a[4] = { 1,2,4,5 };//源链表L1.CreateList(a, 4);L1.Disp();//源链表反向输出InverseList(L1, L2);L2.Disp();}


原创粉丝点击