#include<stdio.h>
#include<stdlib.h>
int count=0;
typedef struct node{
int value;
struct node *next;
}*Node;
//尾插
void insert(int value,Node head){
Node p=head;
while(p->next){
p=p->next;
}
Node temp=(Node)malloc(sizeof(struct node));
temp->value=value;
temp->next=p->next;
p->next=temp;
}
//打印
void print(Node head){
Node p=head->next;
while(p){
printf("%d ",p->value);
p=p->next;
}
}
//反转递归
Node reverse2(Node head){
if(head==NULL||head->next==NULL){
return head;
}else{
Node newhead=reverse2(head->next);
head->next->next=head;
head->next=NULL;
return newhead;
}
}
//反转 非递归 尾插法
void reverse3(Node head){
if(head==NULL||head->next==NULL){
printf("链表为空");
}else{
Node p=head->next;
Node q=p;
while(p){
Node temp=p->next;
p->next=head->next;
head->next=p;
p=temp;
}
q->next=NULL;
}
}
//反转 非递归
void reverse(Node head){
if(head!=NULL&&head->next!=NULL){
Node p=head->next,q=p->next,temp;
if(q==NULL){
return;
}
p->next=NULL;
while(q->next){
temp=q->next;
q->next=p;
p=q;
q=temp;
}
q->next=p;
head->next=q;
}else{
printf("链表为空");
}
}
int main(){
Node head=(Node)malloc(sizeof(struct node));
head->next=NULL;
for(int i=0;i<20;i++){
insert(i,head);
}
//head->next=reverse2(head->next);
// reverse3(head);
reverse(head);
print(head);
}
单链表反转
最新推荐文章于 2021-05-21 11:43:48 发布