NashZhou

广告算法工程师,目前致力于关键词广告的效果自动优化

List.h

View Code
1 typedef int ElemType
2 typedef struct node
3 {
4 ElemType data;
5 struct node *next;
6 }LNode;
7
8
9 void setnull(SNode *&p)//置空表setnull(p)
10 {
11 p=(SNode *)malloc(sizeof(SNode));
12 p->next=NULL;
13 }
14 int length(SNode *&p)//求长度 头结点不算
15 {
16 int n=0;
17 SNode *q=p->next;
18 while(q!=NULL)
19 {
20 n++;
21 q=q->next;
22 }
23 return(n);
24 }
25 SNode *get(SNode *&p,int i)//取单链表中第i个结点地址get(p,i)
26 {
27 int j=0;
28 SNode *q=p->next;
29 while(j<i&&q!=NULL)
30 {
31 q=q->next;
32 j++;
33 }
34 if(q!=NULL)
35 return q;
36 else
37 {
38 cout<<"get error 位置参数i不正确\n";
39 return NULL;
40 }
41 }
42 int locate(SNode *&p,ElemType x)//按值查找locate(p,x)
43 {
44 int i=0;
45 SNode *q=p->next;
46 while(q!=NULL&&q->data!=x)
47 {
48 q=q->next;
49 i++;
50 }
51 if(q==NULL)
52 {
53 cout<<"locate error q==NULL\n";
54 exit(1);
55 }
56 else
57 return i;
58 }
59 void insnode(SNode *&p,ElemType x,int i)//插入结点 insnode(p,x,i) 0<=i<=n
60 {
61 SNode *s,*q;
62 s=(SNode*)malloc(sizeof(SNode));
63 s->data=x;
64 if(i==0)
65 {
66 s->next=p->next;
67 p->next=s;
68 }
69 else
70 {
71 q=get(p,i-1);
72 if(q==NULL)
73 {
74 cout<<"insnode error 位置参数不正确\n";
75 }
76 else
77 {
78 s->next=q->next;
79 q->next=s;
80 }
81 }
82 }
83 void delnode(SNode *&p,int i)//删除结点delnode(p,i)
84 {
85 SNode *q,*t;
86 if(i==0)
87 {
88 t=p->next;
89 p->next=t->next;
90 free(t);
91 }
92 else
93 {
94 q=get(p,i-1);
95 if(p==NULL)
96 { cout<<"delnode error 位置参数不正确\n";exit(1);}
97 else
98 {
99 t=q->next;
100 q->next=t->next;
101 free(t);
102 }
103 }
104 }
105 void display(SNode *p)
106 {
107 int n=length(p),i;
108 SNode *q=p->next;
109 cout<<"单链表显示:";
110 if(n==0)
111 cout<<"空表\n";
112 else if(n==1)
113 cout<<q->data;
114 else
115 {
116 for(i=1;i<n;i++)
117 {
118 cout<<q->data<<"->";
119 q=q->next;
120 }
121 cout<<q->data;
122 }
123 cout<<endl;
124 }
125 void UnionSNode(SNode *&ha,SNode *&hb,SNode *&hc)//ha与hb都是单调递增 求并 且保持hc中仍单调递增
126 {
127 SNode *p,*q,*r;
128 r=hc;p=ha;q=hb;
129 int i=0;
130 while(p!=NULL&&q!=NULL)
131 {
132 if(p->data<q->data)
133 {
134
135 insnode(r,p->data,i++);
136 p=p->next;
137 }
138 else if(p->data>q->data)
139 {
140 insnode(r,q->data,i++);
141 q=q->next;
142 }
143 else
144 {
145 insnode(r,p->data,i++);
146 p=p->next;
147 q=q->next;
148 }
149 }
150 if(q!=NULL) p=q;
151 if(p!=NULL)
152 while(p!=NULL)
153 {
154 insnode(r,p->data,i++);
155 p=p->next;
156 }
157 hc=hc->next;
158 }

posted on 2011-05-16 18:16  NashZhou  阅读(148)  评论(0编辑  收藏  举报

导航