单链表几种操作
代码
1 /*
2 purpose:实现链表的几种操作
3 */
4 #include "stdio.h"
5 #include "stdlib.h"
6 #include "malloc.h"
7
8 struct SNode
9 {
10 int ivalue;
11 struct SNode* next;
12 };
13
14 /************************************************************************/
15 /* Tail insert */
16 /************************************************************************/
17 SNode* createLinkList()
18 {
19 SNode* head,*s,*p;
20 int ix;
21 char ch;
22 head=(SNode*)malloc(sizeof(struct SNode));
23 if(NULL==head)
24 exit(1);
25 head->next=NULL;
26 p=head;
27 while (scanf_s("%d",&ix)==1)
28 {
29 s=(SNode*)malloc(sizeof(struct SNode));
30 if(NULL==s)
31 exit(1);
32 s->ivalue=ix;
33 p->next=s;
34 p=s;
35 }
36 p->next=NULL; //No loop
37 //p->next=head; //Loop linklist
38 return head;
39 }
40
41 /************************************************************************/
42 /* print */
43 /************************************************************************/
44 void printLinkList(SNode* pNode)
45 {
46 if(NULL==pNode)
47 exit(1);
48 SNode* p;
49 p=pNode->next;
50 //while (p!=pNode) //Loop
51 while(p!=NULL) //No loop
52 {
53 printf("%d ",p->ivalue);
54 p=p->next;
55 }
56 printf("\n");
57 }
58
59 /************************************************************************/
60 /* IsLoop */
61 /************************************************************************/
62 bool IsLoop(SNode* pNode)
63 {
64 SNode* p=pNode;
65 SNode* q=pNode;
66 while (q!=NULL && q->next!=NULL)
67 {
68 p=p->next;
69 q=q->next->next;
70 if (p==q)
71 return true;
72 }
73 return false;
74 }
75
76
77
78 int main()
79 {
80 SNode* sNode;
81 sNode=createLinkList();
82 printLinkList(sNode);
83 bool im=IsLoop(sNode);
84 if(im)
85 printf("true\n");
86 else
87 printf("false\n");
88 return 0;
89 }
posted on 2010-10-29 01:00 marrywindy 阅读(331) 评论(0) 收藏 举报

浙公网安备 33010602011771号