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

来源:互联网 发布:vue.js ide 编辑:程序博客网 时间:2024/06/06 01:37

单链表的反转,虽然想起来容易,但是要实现一个没有错误的可运行代码却没那么简单。代码如下

#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;}