码迷,mamicode.com
首页 > 其他好文 > 详细

Alogorim:链表原地反转Demo

时间:2016-06-04 10:28:48      阅读:277      评论:0      收藏:0      [点我收藏+]

标签:

  现在就是Qt开发和给师弟师妹讲下数据结构吧,感觉还挺漫长的,上个Qt帖子等我把成品做出来再更。

 1 //Convert_plug.h
 2 
 3 #ifndef CONVERT
 4 #define CONVERT
 5 
 6 #define MAX 81
 7 typedef char NmaeType; 
 8 typedef struct _name_list
 9 {
10     NmaeType name[81];
11     struct _name_list *next;
12 }Name_List;
13 
14 void convert_the_list(Name_List **);
15 void print_list(Name_List *const, const char *);
16 
17 #endif // !CONVERT
 1 //Convert.cpp
 2 
 3 #include "convert_plug.h"
 4 #include <stdio.h>
 5 #include <stdlib.h>
 6 
 7 int main(int argc, char *argv[])
 8 {
 9     FILE *fp = fopen("D:\\input.txt", "r");
10     Name_List *head = NULL, *tmpCell = NULL, *listPre = NULL;
11 
12     for (;!feof(fp);)
13     {
14         tmpCell = (Name_List *)malloc(sizeof(Name_List));
15         fscanf(fp, "%s", tmpCell->name);
16 
17         if (!listPre)
18             head = tmpCell;//如果是空链表则创建链表头
19         else         
20             listPre->next = tmpCell;//如果不是,则上一个链表要连到当前链表上
21 
22         listPre = tmpCell, listPre->next = NULL;
23     }
24     print_list(head,"反转前:");
25     convert_the_list(&head);
26     print_list(head,"反转后:");
27 
28     fclose(fp);
29     system("pause");
30     return 0;
31 }
32 
33 void print_list(Name_List *const listHead, const char *inform)
34 {
35     //输出所有链表的值
36     Name_List *tmpCell = listHead;
37     printf("%s", inform);
38     for (; tmpCell != NULL; tmpCell = tmpCell->next)
39         printf("%s ", tmpCell->name);
40     printf("\n");
41 }
42 
43 void convert_the_list(Name_List **listHead)
44 {
45     if (listHead == NULL)
46         return;
47     Name_List 
48           *listTmpCur = *listHead
49         , *listTmpNext = (*listHead)->next
50         , *listTmpPre = NULL;
51 
52     for (;listTmpNext != NULL;)
53     {
54         listTmpCur->next = listTmpPre;
55         listTmpPre = listTmpCur;
56         listTmpCur = listTmpNext;
57         listTmpNext = listTmpNext->next;
58     }
59     listTmpCur->next = listTmpPre;
60     *listHead = listTmpCur;
61 
62 }

 

Alogorim:链表原地反转Demo

标签:

原文地址:http://www.cnblogs.com/Philip-Tell-Truth/p/5558216.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!