/*反转单链表*/ #includestdio.h #include stdlib.h #define len sizeof(struct A) struct A { int num; struct A * next;}; int m; struct A *creat( int n) //创建结点个数为n的单链表 { struct A *head, *p1, * p2; m = 0 ; p1 = p2 = ( s
/*反转单链表*/
#include<stdio.h> #include<stdlib.h> #define len sizeof(struct A) struct A { int num; struct A *next; }; int m; struct A *creat(int n)//创建结点个数为n的单链表 { struct A *head, *p1, *p2; m = 0; p1 = p2 = (struct A *)malloc(len); scanf("%d", &p1->num); head = NULL; while (m < n) { m = m + 1; if (m == 1) { head = p1; } else { p2->next = p1; } p2 = p1; if (m < n) { p1 = (struct A*)malloc(len); scanf("%d", &p1->num); } } p2->next = NULL; return head; } void print(struct A * head)//打印单链表 { struct A *p; p = head; if (head != NULL) { do { printf("%d ", p->num); p = p->next; } while (p != NULL); } } struct A* inverse(struct A* head)//反转单链表 { struct A *p1, *p2,*r; p2 = head; p1 = head->next; head->next = NULL; while (p1) { r = p1->next; p1->next = p2; p2 = p1; p1 = r; } head = p2; return head; } int main() { printf("输入链表中结点的数目:\n"); int n; scanf("%d", &n); printf("输入%d个结点:\n", n); struct A * head; head = creat(n); head=inverse(head); printf("输出链表中的结点:\n"); print(head); return 0; }
参考单链表反转CSDN博客
https://blog.csdn.net/feliciafay/article/details/6841115 反转过程非常清楚