【发布时间】:2013-07-01 08:27:52
【问题描述】:
最近我在一次采访中被问到这个问题。我所能做的就是从一个从0到9开始的链表从9到1遍历。代码如下:
#include <iostream>
typedef struct node {
int data; // will store information
node *next; // the reference to the next node
};
node *head;
int printList(node *traverse) {
if (traverse->next == NULL) {
return -1;
}
traverse=traverse->next;
printList(traverse);
cout << traverse->data << endl;
return 0;
}
int main() {
node *temp = NULL;
node *begin = NULL;
for (int i = 0; i < 10; i++) {
temp = new node;
temp->data = i;
if (begin == NULL) {
begin = temp;
}
if (head != NULL) {
head->next = temp;
}
head = temp;
head->next = NULL;
}
head = begin;
printList(head);
return 0;
}
1) 如何使用 printList() 递归函数打印 0(第一个元素)?
2) 如何用 while 循环替换 printList() 递归函数?
3) 如果在采访中被问到,main() 函数是否有正确的节点初始化和插入?
【问题讨论】:
-
我的错误。删除评论以防止混淆。
标签: c++ linked-list traversal singly-linked-list