单向链表的反转问题

 1 #ifndef LIST_H_INCLUDED
 2 #define LIST_H_INCLUDED
 3 #include <stdio.h>
 4 #include <stdlib.h>
 5 #define L_TYPE char
 6 typedef struct Node node;
 7 typedef struct Node* Plist;
 8 typedef Plist  List;
 9 
10 struct  Node
11 {
12     L_TYPE element;
13     Plist next;
14 };
15 Plist Creatlist();    //creat a list note:hava an head node;
16 void Delete(Plist list);//delete an element of the list
17 void Insert_list(Plist list,L_TYPE element);// insert an element into the list
18 int L_isEmpty(Plist list);// judge whether the list is empty or not  if is empty return an integer else return 0;
19 Plist ReverseList(Plist list);// reverse the list  not : the parameter list is not the head node but next node of head node
20                               //(if your list has no head node you can use this function directly)
21 Plist ReverseList(Plist list);
22 
23 Plist Creatlist()
24 {
25     Plist list=(List)malloc(sizeof(node));
26     list->next=NULL;
27     return list;
28 
29 }
30 void Delete(Plist list)
31 {
32     Plist temp;
33     if(!L_isEmpty(list))
34     {
35         temp=list->next;
36         list->next=list->next->next;
37     }
38     else
39     {
40         printf("List is empty!");
41     }
42 }
43 void Insert_list(Plist list,L_TYPE element)
44 {
45     Plist templist=(List)malloc(sizeof(node));
46     templist->element=element;
47     templist->next=list->next;
48     list->next=templist;
49 
50 }
51 int L_isEmpty(Plist list)
52 {
53     return !list->next;
54 }
55 
56 void Printlist(Plist list)
57 {
58     Plist plist=list;
59     while(plist->next)
60     {
61         printf("%c\n",plist->next->element);
62         plist=plist->next;
63     }
64 }
65 
66 Plist ReverseList(Plist list)
67 {
68    Plist next;
69    Plist previous=NULL;
70    while(list)
71    {
72        next=list->next;
73        list->next=previous;
74        previous=list;
75        list=next;
76    }
77    return previous;
78 }
79 
80 
81 
82 #endif // LIST_H_INCLUDED
list.h

反转链表的简单解释;

 

 

注:我定义的单向链表有头结点;

所以下面代码中反转,多出一步头结点指向新链表头的步骤 如下图;

主函数代码;反转函数为 Plist ReverseList(Plist list)

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include "list.h"
 4 int main()
 5 {
 6     int i;
 7     Plist list=Creatlist();
 8     for(i=0;i<5;i++)
 9     {
10       Insert_list(list,'A'+i);
11     }
12     Printlist(list);
13     printf("-----------------------------\n");
14     // reverse the list (with head node) there is little different from the list without head node for eg. below;
15     list->next=ReverseList(list->next);
16     //print the list
17     Printlist(list);
18 
19 return 0;
20 
21 }
list.c

 

 

 

posted on 2014-04-26 12:04  阿南要加油  阅读(346)  评论(0编辑  收藏  举报

导航