链表逆序

要求实现函数:

void converse(ListNode **head);

 【输入】head:    链表头节点,空间已经开辟好

 【输出】head:    逆序后的链表头节点

 【返回】无

 【注意】只需要完成该函数功能算法,中间不需要有任何IO的输入输出

 示例

输入:链表  1->2->3->4->5 的头节点head

 输出:链表  5->4->3->2->1 的头节点head

 

 1 #include<iostream>

 2 #include<string>

 3 #include<vector>

 4 #include<algorithm>

 5 #include<stack>

 6 #include<map>

 7 #include<sstream>

 8 using namespace std;

 9 

10 typedef struct tagListNode

11 {

12     int value;

13     struct tagListNode *next;

14 }ListNode;

15 

16 void converse(ListNode **head)

17 {

18     ListNode* h1 = *head;

19     if(h1==NULL)

20         return;

21 

22     ListNode *p, *q;

23     p = h1;

24     q = p->next;

25 

26     while(q!=NULL)

27     {

28         ListNode *temp = q;

29         q = q->next;

30         temp->next = p;

31         p = temp;

32     }

33     h1->next = NULL;

34     h1 = p;

35 

36     //head = &h1;  //这样写不能把逆序后的头指针传回去

37     *head = h1;

38 }

39 

40 int main()

41 {

42     int val;

43     ListNode *h = NULL;

44     ListNode *last=NULL, *p=NULL;

45     

46     while(cin>>val)

47     {

48         if(h==NULL)

49         {

50             h = new ListNode;

51             h->value = val;

52             last = h;

53         }

54         else

55         {

56             p = new ListNode;    

57             p->value = val;    

58             last->next = p;

59             last = p;

60         }

61     }

62     if(last!=NULL)

63         last->next = NULL;

64 

65     converse(&h);

66 

67     ListNode *cur = h;

68     while(cur!=NULL)

69     {

70         cout<<cur->value<<" ";

71         cur = cur->next;

72     }

73     

74     return 0;

75 }

 

运行结果:

你可能感兴趣的:(链表)