找回密码
 立即注册→加入我们

QQ登录

只需一步,快速开始

搜索
热搜: 下载 VB C 实现 编写
查看: 3274|回复: 0

【算法】链表翻转

[复制链接]

33

主题

1

回帖

561

积分

用户组: 大·技术宅

UID
580
精华
26
威望
28 点
宅币
341 个
贡献
0 次
宅之契约
0 份
在线时间
8 小时
注册时间
2014-12-8
发表于 2015-1-11 12:57:32 | 显示全部楼层 |阅读模式

欢迎访问技术宅的结界,请注册或者登录吧。

您需要 登录 才可以下载或查看,没有账号?立即注册→加入我们

×
  1. #include <iostream>
  2. using namespace std;

  3. struct Node
  4. {
  5.         int key;
  6.         Node* next;
  7. };
  8. Node* createList(int arr[],int nLength);
  9. Node* reverseList(Node* head);
  10. void printList(Node* head);
  11. void clearList(Node* head);

  12. void main()
  13. {
  14.         int arr[] = {1,3,5,7,9};
  15.         int nLength = sizeof(arr)/sizeof(arr[0]);
  16.         Node* head = createList(arr,nLength);
  17.         printList(head);
  18.         head = reverseList(head);
  19.         printList(head);
  20.         clearList(head);
  21. }

  22. Node* createList(int arr[],int nLength)
  23. {
  24.         Node* head = new Node;
  25.         head->key = arr[0];
  26.         head->next = NULL;
  27.         Node *p = head;
  28.         for(int i=1;i<nLength;i++)
  29.         {
  30.                 Node* ptr = new Node;
  31.                 ptr->key = arr[i];
  32.                 ptr->next = NULL;
  33.                 p->next = ptr;
  34.                 p = p->next;
  35.         }
  36.         return head;
  37. }

  38. Node* reverseList(Node* head)
  39. {
  40.         Node* preNode = NULL;
  41.         Node* pNode = head;
  42.         while( pNode != NULL )
  43.         {
  44.                 Node* pNext = pNode->next;
  45.                 pNode->next = preNode;
  46.                 preNode = pNode;
  47.                 pNode = pNext;

  48.         }
  49.         return preNode;
  50. }

  51. void printList(Node* head)
  52. {
  53.         Node* p = head;
  54.         while( p!= NULL )
  55.         {
  56.                 cout<<p->key<<endl;
  57.                 p=p->next;
  58.         }
  59. }

  60. void clearList(Node* head)
  61. {
  62.         Node* p = head;
  63.         Node* ptr;
  64.         while( p!= NULL )
  65.         {
  66.                 ptr = p->next;
  67.                 delete p;
  68.                 p = ptr;
  69.         }
  70. }
复制代码
回复

使用道具 举报

QQ|Archiver|小黑屋|技术宅的结界 ( 滇ICP备16008837号 )|网站地图

GMT+8, 2024-4-20 11:44 , Processed in 0.039793 second(s), 31 queries , Gzip On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表