链表的逆置(带表头的单向链表)
#include#include #define N 9 typedef struct node{ int data; struct node * next; }ElemSN; ElemSN * Createlink(int a[],int n) { int i; ElemSN * h, * p; h=p=(ElemSN *)malloc(sizeof(ElemSN)); h->next=NULL; for( i=0;i next=(ElemSN *)malloc(sizeof(ElemSN)); p->data =a[i]; p->next=NULL; } return h; } void printlink(ElemSN * h){ ElemSN * p; for(p=h;p->next;p=p->next) printf("%2d\n",p->next->data); } void Prelink(ElemSN*h){ ElemSN*p,*r; r=h->next; //头指针后移,给r指针 h->next=NULL; //h断开,避免形成环(是一个头指针与第一个结点的环) while(r){//头指针为空,链表遍历完 p=r; //当前的结点 r=r->next;//r后移(头指针),保证链表有头指针 p->next=h->next;//挂链(逆置) h->next=p;//建立新的头结点 } } int main(void){ int a[N]={1,2,3,4,5,6,7,8,9}; ElemSN * head; head=Createlink(a,9); Prelink(head); printlink(head); }
标题名称:链表的逆置(带表头的单向链表)
分享网址:http://ybzwz.com/article/ijoogo.html