链表结构反转的思想:
将一个链表分为3部分,head(头部分),mid(中间部分),last(最后部分);
反转前的顺序:head->mid->last;
反转后的顺序:last->mid->head;
因此,将last向head方向移动,head向last方向移动,最终使mid成为head的前结点,last成为mid的前结点。
llink inverllist(llink head)
{ llink mid,last; mid=NULL; //mid是head的前结点 while(head!=NULL) { last=mid; //last是mid的前结点 mid=head; head=head->next; //下一个结点 mid->next=last; //mid指向前结点last } return mid; }举例如下,
链表的反转
#include " stdio.h " #include " stdlib.h " struct llist { int num; struct llist * next;}; typedef struct llist node; typedef node * llink; /* ------------链表的输出---------- */ void printllist( llink ptr) { while (ptr != NULL) { printf( " [%d] " ,ptr -> num); ptr = ptr -> next; } printf( " \n " ); } /* --------链表的创建-------- */ llink createllist( int * array , int len) { llink head; llink ptr,ptr1; int i; /* ------创建第一个结点------ */ head = (llink)malloc( sizeof (node)); if ( ! head) return NULL; head -> num = array[ 0 ]; head -> next = NULL; ptr = head; for (i = 1 ;i < len;i ++ ) { ptr1 = (llink)malloc( sizeof (node)); if ( ! ptr1) return NULL; ptr1 -> num = array[i]; ptr1 -> next = NULL; ptr -> next = ptr1; ptr = ptr -> next; } return head; } /* --------链表的反转------ */ llink inverllist(llink head) { llink mid,last; mid = NULL; while (head != NULL) { last = mid; mid = head; head = head -> next; mid -> next = last; } return mid; } /* -------链表的内存释放------- */ void freellist(llink head) { llink ptr; while (head != NULL) { ptr = head; head = head -> next; free(ptr); } } /* ------反转链表--------- */ int main(){ int llist[ 6 ] = { 1 , 2 , 3 , 4 , 5 , 6 }; llink head; head = createllist(llist, 6 ); if ( ! head) { printf( " 内存分配失败! \n " ); exit( 1 ); } printf( " 原来的链表: " ); printllist(head); head = inverllist(head); printf( " 反转后链表: " ); printllist(head); freellist(head);}