栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > C++面试题库

用递归实现链表逆序

用递归实现链表逆序

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

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/265650.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号