3道经典面试题

wx1234567 2004-11-20 08:38:02
A. Given a link list of integers, write a procedure PrintReverse() to print out the integers in reverse order. e.g. if mylist is 3, 6, 2, then PrintReverse(mylist) would print out 2 6 3.
Notes:
1. please handle all special cases
2. mylist has to be the same as before after PrintReverse() has run.


typedef struct node
{
int x;
struct node* next;
} Node;

void PrintReverse(Node* mylist)
{
…. Your code goes here …
}

B. What is the time complexity of your procedure?

C. What is the space complexity of your procedure?
...全文
303 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Flood1984 2004-11-20
  • 打赏
  • 举报
回复
上面的都是先进栈,然后出栈,
相当与每个元素访问2次,须占用空间n
还有更好一点的吗?
楼下继续
jussoo 2004-11-20
  • 打赏
  • 举报
回复
__...---^^^^^---...__
_.-^^ ^^-._
./' `\.
_/' `\_
/' `\
/ \
|' `|
__' `__
____.---^^^^-. .-^^^^---.____
\_ ( __,--^^-._ ^. .^ _.-^^--.__ ) _/
`\_ `-^ | `\ \ / /' | ^-' _/'
|\`\_ | \ \ / / | _/'/|
|`|`\`\_ .| \ \ . / / |. _/'/'|'|
| | `\`\_ |' | \ | / | `| _/'/' | |
`| /`\`\ || | || /'/'\ |'
| :' \,|' .._ _.. `|.' `: |
`| | / ^=._ _.=^ \ | |'
| d^^^xxx.__ `|' __.xxx^^^b |
`| d#. 9XX^^\\^^--..__ | __..--^^//^^XX #b |'
| |##x__ | \ ^^Xx..__ | __..xX^^ / | __x#| |
\ ^^ | \_ _/^ ^\_ _/ | ^^ /
`-._ | ^^-----...-^ ^-...-----^^ |' _.-'
^-._ `| ^^-------^^^^ | ^^^^-------^^ | _.-^
^- || .| || -^
|^|| l| ||^|
| | .d|xx. | |
|' `| |' `|
| |; ..----. ;| |
| |X\._ ^ __ _./X| |
|' | ^-._ .X""^^^ _.-^ | `|
| | \^-._ _.-^/ | |
___|, `| `\\^-._ _.-^//' |' `|___
..---^^^^ | | `\\\^-.___.-^///' | | ^^^^---..
| `| `\\XXX//' |' |
| | `| ^^^ |' | |
`| `| `| |' |' |'
\ \ / /
..........------------------.....__ __.....-------------------..........
^\ /^
\v/
|
|
___ | __
#######xxxxxx_____ | _____xxxxxx#######
#######################xxxxxxxxxx___ | ___xxxxxxxxxx#######################
#############################################################################
WuYL7812 2004-11-20
  • 打赏
  • 举报
回复
pop one at a time and print it.
WuYL7812 2004-11-20
  • 打赏
  • 举报
回复
push all the Elements into a stack, and then pop out all element, pop one at a time and print them.
time complexity: O(n)
space complexity: O(n)
xiaolizi 2004-11-20
  • 打赏
  • 举报
回复
真是不好意思,两个地方要修改一下

void PrintReverse(Node* mylist)
{
int size = 1;
int* buf = 0;
int id = 0;

while(mylist)
{
if(id >= size)
{
size *= 2;
buf = (int*)realloc(buf, size);
}
buf[id++] = mylist->x;
mylist = mylist->next;
}

if(size > 0)
{
while(id >= 0)
{
print(buf[id--]);
}

free(buf);
}
}
xiaolizi 2004-11-20
  • 打赏
  • 举报
回复
void PrintReverse(Node* mylist)
{
int size = 1;
int* buf = (int*)malloc(size);
int id = 0;

while(mylist->next)
{
if(id >= size)
{
size *= 2;
buf = (int*)realloc(buf, size);
}
buf[id++] = mylist->x;
mylist = mylist->next;
}

while(id > 0)
{
print(buf[id--]);
}

free(buf);
}


时间和空间的取舍,写程序总会碰到这样的问题,
抽象出来,生活中又何尝不是这样,时间万物又何尝不是这样

15,440

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧