数据结构之链表(c语言实现)
题目:逆置链表。
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node * next;
}ElemSN;
ElemSN * createlink(int data[],int n)
{
ElemSN *h=NULL,*t,*newp;
int i;
for( i=0;i<n;i++)
{
newp=(ElemSN *)malloc(sizeof(ElemSN));
newp->data=data[i];
newp->next=NULL;
if(!h)
h=t=newp;
else
t=t->next=newp;
}
return h;
}
void printlink(ElemSN *h)
{
ElemSN *p;
p=h;
for(p=h;p;p=p->next)
printf("%5d",p->data);
}
ElemSN *nizhi(ElemSN *h)//逆置,实际上相邻的两个元素交换位置,然后后面位置的元素再头插。
{
ElemSN *p,*q=h;
for(p=h->next;p;p=q->next)
{
q->next=p->next;
p->next=h;
h=p;
}
return h;
}
int main(void)
{
int data[8]={1,2,3,4,5,6,7,8};
ElemSN * head;
head=createlink(data,8);
printlink(head=nizhi(head));
}