用递归实现链表逆序

匿名网友 匿名网友 发布于: 2015-08-30 00:00:00
阅读 132 收藏 0 点赞 0 评论 0

C语言风格的代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
const int M=10;
typedef int Type;
typedef struct Node{
Type data;
struct Node* next;
}Node;
void add_elem(Node **head,Type data){
Node* tmp = (Node*)malloc(sizeof(Node));
tmp->data = data;
tmp->next = (*head);
*head = tmp;
}
void print_list(Node *head){
while(head){
printf(“%d “, head->data);
head = head->next;
}
printf(“n”);
}

void reverse_list(Node **head){
if(!*head)//如果(*head)==NULL
return;
Node *p1,*p2;
p1 = *head;
p2 = (*head)->next;
if(!p2)//如果没有下一个节点

return;
reverse_list(&p2);//同时存在两个节点就要进行翻转

p1->next->next = p1;
p1->next = NULL;//主要是保证,第一个节点指向NULL

(*head) = p2;
}
int main(){
Node *head = NULL;
for(int i=0;i<M;i++)
add_elem(&head, rand()%100);
print_list(head);
reverse_list(&head);
print_list(head);
}

 

评论列表
文章目录