链表逆序

实现链表逆序的功能

下面是实现链表逆序的函数:

 1 /*
 2  * 把head指针指向的链表逆序
 3  * author:rio_2607
 4  */
 5 void inverse(struct node *head)
 6 {
 7     struct node *current = head;
 8     struct node *current_next = NULL;
 9 
10     //如果是一个空链表或者只有一个元素,则直接返回
11     if(NULL == head || NULL == current->next)
12         return;
13 
14     current_next = current->next;
15 
16     while(current_next->next != NULL)
17     {
18         struct node *temp = current_next->next;
19         current_next->next = current;//逆序指针
20 
21         current = current_next;//两个指针都往后移一个
22         current_next = temp;
23     }
24 
25     //把最后两个节点逆序
26     current_next->next = current;
27     head->next = NULL;
28 
29     head = current_next;//把头指针指向最后一个指针
30 
31 
32     //打印输出结果
33     struct node *t = head;
34     while(t != NULL)
35     {
36         cout << t->data << "  ";
37         t = t->next;
38     }
39 
40 }

其中,struct node的定义是:

1 struct node {
2     int data;
3     struct node *next;
4 };

下面是测试代码:先输入链表的长度,在依次输入每个链表的数据域的数据,然后分别打印输出逆序前后的数据:

 1 int main()
 2 {
 3     struct node *head = NULL;
 4     struct node *current = NULL;
 5     int number;
 6     cout << "please enter the number :" ;
 7     cin >> number;
 8     for(int i = 1;i <=number;++i)
 9     {
10         struct node *temp = (struct node*)new struct node;
11         cin >> temp->data;
12         temp->next = NULL;
13 
14         if(NULL == head)
15             head = temp;
16         else
17             current->next = temp;
18 
19         current = temp;
20 
21     }
22 
23 
24     //打印数据
25     struct node *t = head;
26     cout << "Before inverse:" << endl;
27     while(t != NULL)
28     {
29         cout << t->data << "  ";
30         t = t->next;
31     }
32 
33     cout << endl;
34 
35     cout << "After inverse:" << endl;
36 
37     inverse(head);//链表逆序
38 
39     return 0;
40 }

运行结果如下所示:

 

posted @ 2015-04-19 19:51  RIO_2607  阅读(357)  评论(1编辑  收藏  举报