(1)算法
1
struct link
2

{
3
int data;
4
struct link *next;
5
};
6
7
link reverse(link x)
8

{
9
if( NULL==x )
10
return NULL;
11
12
link t=NULL;
13
link r=NULL, y=x; //(0)
14
while(y!=NULL)
15
{
16
t = y->next; //(1)
17
y->next = r; //(2)
18
r = y; //(3)
19
y = t; //(4)
20
}
21
22
return r; //返回逆置后的链表
23
}
24
(二)原理
(0)(1)(2)(3)(4)分别对应以上程序的各序号
第一次while循环
-------------------------------------------
(0) r=NULL, y=x
r=NULL a ---> b ---> c ---> d --> NULL
|(0)
y
-------------------------------------------
(1) t =y->next
r=NULL a ---> b ---> c ---> d --> NULL
|(0) | (1)
y t
--------------------------------------------
(2) y->next = r
a ---> NULL b ---> c ---> d --> NULL
|(0) (2) | | (1)
y r t
---------------------------------------------
(3) r = y
a ---> NULL b ---> c ---> d --> NULL
|(0) (2) | (1)
y t
|(3)
r
---------------------------------------------
(4) y = t
a ---> NULL b ---> c ---> d --> NULL
|(0) (2) | (1)
| t
|(3) | (4)
r y
第二次while循环(并对上面进行整理)
---------------------------------------------
(1) t = y->next
a ---> NULL b ---> c ---> d --> NULL
| | |(1)
r y t
---------------------------------------------
(2) y->next = r
b ---> a ---> NULL c ---> d --> NULL
| (2) | |(1)
y r t
---------------------------------------------
(3) r = y
b ---> a ---> NULL c ---> d --> NULL
| (2) |(1)
y t
| (3)
r
---------------------------------------------
(4) y = t
b ---> a ---> NULL c ---> d --> NULL
| (2) |(1)
| t
| (3) |(4)
r y
第三个循环 (并对上面的进行整理)
---------------------------------------------
(1) t = y->next
b ---> a ---> NULL c ---> d --> NULL
| | |(1)
r y t
以后的与第二次循环同, 最终可得:
d ---> c ---> b ---> a ---> NULL
posted on 2009-07-19 11:56
老马驿站 阅读(1075)
评论(0) 编辑 收藏 引用 所属分类:
c++