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

2013年百度实习生面试 编程题之--单链表的反转

2013-05-16 21:58 274 查看
单链表的反转,虽然想起来容易,但是要实现一个没有错误的可运行代码却没那么简单。代码如下

#include<stdio.h>
#include<stdlib.h>

typedef struct{
int value;
struct node_t* next;
}node_t;
node_t* head;
void buildLink(int);
void printLink();
void buildLink(int n){
int i=0;
node_t* tmp;
node_t* tmpnode;
if(n>=1){
head = malloc(sizeof(node_t));
head->value = rand()%99;
tmp = head;
for(i=1;i<n;i++){
tmpnode = malloc(sizeof(node_t));
tmpnode->value = rand()%99;
//			printf("value of node %d\n",i);
//			scanf("%d",&tmpnode->value);
tmp->next = tmpnode;
tmp = tmp->next;
}
}
}
void printLink(){
int i =0;
node_t* first = head;
while(first!=NULL){
printf("node %d 's value is %d\n ",i,first->value);
first=first->next;
i++;
}
}
void revirse(){
node_t* first = head;
node_t* tmp;
node_t* afterTmp;
if(head==NULL)
return;
tmp = first->next;
if(tmp==NULL)
return;
afterTmp = tmp->next;
while(afterTmp!=NULL){
tmp->next = first;
first = tmp;
tmp = afterTmp;
afterTmp = afterTmp->next;
}
tmp->next = first;
head->next =NULL;
head = tmp;
}
int main(void){
int i =0;
printf("input node number\n");
scanf("%d",&i);
buildLink(i);
printf("before revirse\n");
printLink();
revirse();
printf("after revirse\n");
printLink();
return 1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: