9.30:单链表的翻转
head.h
#ifndef __HEAD_H__
#define __HEAD_H__
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}*linklist;
linklist create();
linklist insert_rear(linklist L , int element);
void output(linklist L);
linklist nizhi(linklist L);
#endif
test.c
#include "head.h"
linklist create()
{
linklist s = (linklist)malloc(sizeof(struct Node));
if(NULL == s)
return NULL;
s->data = 0;
s->next = NULL;
return s;
}
linklist insert_rear(linklist L , int element)
{
linklist s = create();
s->data = element;
if(NULL == L)
L = s;
else
{
linklist p = L;
while(p->next != NULL)
{
p = p->next;
}
p->next = s;
}
return L;
}
void output(linklist L)
{
linklist p = L;
if(NULL == L)
{
printf("链表为空\n");
return;
}
else
{
while(p != NULL)
{
printf("%d ",p->data);
p = p->next;
}
}
puts("");
}
linklist nizhi(linklist L)
{
if( NULL == L || NULL == L->next)
return L;
else
{
linklist p = L->next;
L->next = NULL;
while(p != NULL)
{
linklist t = p;
p = p->next;
t->next = L;
L = t;
}
}
return L;
}
main.c
#include "head.h"
int main(int argc, const char *argv[])
{
linklist L = NULL;
int i = 0;
int n = 0;
int element = 0;
printf("输入多少元素:");
scanf("%d",&n);
for(i = 0 ; i < n ; i++)
{
printf("输入元素:");
scanf("%d",&element);
L = insert_rear(L,element);
}
output(L);
L = nizhi(L);
output(L);
return 0;
}
运行结果