//链表逆序
#include <stdio.h>
#include <stdlib.h>
#define N 8
typedef struct list
{ int data;
struct list *next;
} SLIST;
void fun(SLIST *h)
{
SLIST *p, *q, *r;
p = h->next;
if (p==0) return;
q = p->next;
p->next = NULL;
while (q)
{
r = q->next; q->next = p;
p = q;
q = r;
}
h->next = p;
}
SLIST *creatlist(int a[])
{
SLIST *h,*p,*q;
int i;
h = (SLIST *)malloc(sizeof(SLIST));
h->next = NULL;
for(i=0; i<N;i++)
{
q=(SLIST *)malloc(sizeof(SLIST));
q->data=a[i];
q->next = NULL;
if (h->next == NULL) h->next = p = q;
else {
p->next = q; p = q;
}
}
return h;
}
void outlist(SLIST *h)
{
SLIST *p;
p = h->next;
if (p==NULL)
printf("The list is NULL!\n");
else
{
printf("\nHead ");
do
{
printf("->%d", p->data); p=p->next;
}
while(p!=NULL);
printf("->End\n");
}
}
main( )
{ SLIST *head; int a[N]={1,2,2,3,4,4,4,5};
head=creatlist(a);
printf("\nThe list before 逆序 :\n"); outlist(head);
fun(head);
printf("\nThe list after 逆序 :\n"); outlist(head);
}
数据结构-链表逆序
最新推荐文章于 2023-11-02 10:23:34 发布