下面提供一个简单的链表倒置方法,
代码如下:
#include<stdio.h> #include<stdlib.h> #define N 10 #define TRUE 1 #define FALSE 0 typedef int data_t; typedef struct node{ data_t data; struct node *next; }linknode,*linklist; /*创建一个空结点*/ void creat_list(linklist *head) { *head = (linklist)malloc(sizeof(linknode)); if(*head == NULL) { printf("malloc error ! \n"); exit(EXIT_FAILURE); } (*head)->next = NULL; } /*求链表的长度*/ data_t length_list(linklist head) { int count = 0; linklist p; p=head; while(p->next != NULL ) { count++; p=p->next; } return count; } /*以固定的顺序插入元素*/ void insert_list(linklist head,data_t x,int i) { linklist p,q; int j=1; if(i<1 || i>length_list(head)+1) { printf("i is wrong!\n"); } p = head; q=(linklist)malloc(sizeof(linknode)); q->data=x; q->next=NULL; while(j<i) { p=p->next; j++; } q->next = p->next; p->next = q; return ; } /*打印链表*/ void display(linklist head) { linklist p; p=head->next; while(p != NULL ) { printf("%d ",p->data); p=p->next; } printf("\n"); return ; } /*使用头插法反转链表*/ void reverse_list(linklist head) { linklist p,q; if(head == NULL) { exit(EXIT_FAILURE); } p=head->next; while(p->next != NULL) { q=p->next; p->next=q->next; q->next=head->next; head->next=q; } return ; } int main(void) { int i=N; linklist head = NULL; creat_list(&head); while(i>0) { insert_list(head,i,1); i--; } display(head); reserve_list(head); display(head); return 0 ; }