链表逆序

 1 #include<stdio.h>

 2 #include<stdlib.h>

 3 

 4 typedef struct NODE

 5 {

 6     int data;

 7     struct NODE *next;    

 8 }Node;

 9 

10 Node* reverse(Node *head)

11 {

12     Node *p1, *p2, *p3;

13 

14     if(head == NULL || head->next == NULL)

15     {

16         return head;

17     }

18     

19     p1 = head;

20     p2 = p1->next;

21 

22     

23     while(p2)

24     {

25         p3 = p2->next;

26         p2->next = p1;

27         p1 = p2;

28         p2 = p3;

29     }

30 

31     head->next = NULL;

32     head = p1;

33 

34     return head;

35 }

36 

37 Node* create()

38 {

39     Node *p, *head, *s;

40     int num;

41     int i, x;    

42 

43     printf("please input the node number:");

44 

45     scanf("%d", &num);

46     if(num <= 0)

47     {

48         printf("error! The input number is wrong!!!\n");

49         return NULL;

50     }

51 

52     head = (Node*)malloc(sizeof(Node));

53     p = head;

54 

55     for(i = 0; i < num; i++)

56     {

57         scanf("%d", &x);

58         s = (Node*)malloc(sizeof(Node));

59         s->data = x;

60         p->next = s;

61         p = s;

62         

63     }

64 

65     head = head->next;

66     p->next = NULL;

67 

68     return head;

69     

70 }

71 

72 void main()

73 {

74     Node *head, *p;

75     head = create();

76     p = reverse(head);

77 

78     while(p)

79     {

80         printf("%d ", p->data);

81         p = p ->next;

82     }

83 

84     printf("\n");

85     

86 }

87 

88  

 

你可能感兴趣的:(链表)