反转链表
来源:互联网 发布:南风知我意晋江书包网 编辑:程序博客网 时间:2024/06/03 06:45
定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
#include <iostream>#include <string.h>#include <stdlib.h>using namespace std;struct Node{int data;struct Node* next;};struct Node* create_list(int len){if (len <= 0)return NULL;struct Node* head;struct Node* tmp;struct Node* pre;for (int i=0; i<len; i++){if (i == 0){head = tmp = new struct Node;tmp->data = i;tmp->next = NULL;pre = tmp;continue;}tmp = new struct Node;tmp->data = i;tmp->next = NULL;pre->next = tmp;pre = tmp;}return head;}void visit(const struct Node *head){ if (head == NULL) return; const struct Node *tmp; tmp = head; while (tmp) { cout << tmp->data << endl; tmp = tmp->next; }}struct Node* reverse(struct Node *head){if (head == NULL)return NULL;struct Node *nex = NULL;struct Node *tmp = NULL;struct Node *pre = NULL;tmp = head;while (1){if (pre == NULL) // first{pre = tmp;nex = tmp->next;tmp = tmp->next;pre->next = NULL;continue;}nex = tmp->next;if (nex == NULL){tmp->next = pre;return tmp;}tmp->next = pre;pre = tmp;tmp = nex;}}void free_list(struct Node *head){if (head == NULL)return;struct Node *tmp;while (head){tmp = head;head = head->next;delete tmp;}}int main(){struct Node *head = create_list(5);visit(head);cout << endl;head = reverse(head);visit(head);free_list(head);return 0;}
0 0
- 链表反转
- 反转链表
- 单向链表反转
- 链表反转:
- 链表的反转
- 链表反转
- 反转单向链表
- 链表反转
- 单向链表反转
- 单向链表反转
- 链表的反转
- 链表反转
- 反转链表
- 链表反转
- 链表反转
- 链表反转
- 链表反转
- 链表的反转
- android多分辨率多屏幕密度下UI适配方案
- Java NIO客户端开发问题
- C++利用gsoap调用webservice
- __declspec(selectany)的作用
- osgAudio编译
- 反转链表
- 利用DHT网络原理制作bt采集蜘蛛
- ogg长事务
- Class文件格式(2)-深入理解ClassFile
- android telephone 4.2 framework层分析
- 五种开源协议(GPL,LGPL,BSD,MIT,Apache)
- destoon在360浏览器下出现用户被强行注销的解决方法
- Android 数据查询query函数参数解析
- eclipse 快捷键大全,eclipse查找类,文件,添加注释