206. Reverse (Linked List)
来源:互联网 发布:淘宝胡公子评价 编辑:程序博客网 时间:2024/05/16 04:36
题目:
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
iteratively
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */struct ListNode* reverseList(struct ListNode* head) { if(head == NULL) return; struct ListNode *pre, *cur, *next; pre = NULL; cur = head; while(cur){//就地 next = cur->next; cur->next = pre; pre = cur; cur = next; } return pre;}
runtime:4ms
recursively
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ // 1->2->3struct ListNode* reverseList(struct ListNode* head) { if(head==NULL){ return head; } struct ListNode *p, *q; p = head; q = head->next; if(q == NULL){ return head; } else{ head = reverseList(q);//递归到最深处始终为3 } q->next = p; p->next = NULL; return head;}
runtime:4ms
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */struct ListNode* reverseList(struct ListNode* head) { struct ListNode *p; p = head; // q = head->next; if(head==NULL || head->next == NULL){//空或最后结点 return head; } head = reverseList(p->next); p->next->next = p; p->next = NULL; return head;}
runtime:0ms
递归分析
递归算法:
- 若只有一个结点,则直接返回;
- 若存在两个结点(a1,a2)则需要做的操作有:
a2->next=a1;a1->next=NULL;return a2;
//a2即新的头结点
- 若有三个结点,则应先将子链(a2,a3)先逆置且返回该子链的新的头结点,然后把子链(a2,a3)当作一个复合结点a2’ //组成新的二元组(a1,a2’)
然后就可以执行前面相同的操作: a2'->next=a1;a1->next=NULL;return a3';
即可;
- 多个结点同理可得。
已经阐述过,我很水,所以就各种参考。
感谢这个和这个。
0 0
- 206. Reverse Linked List
- 206. Reverse Linked List
- 206. Reverse Linked List
- 206. Reverse Linked List
- 206. Reverse Linked List
- 206. Reverse Linked List
- 206. Reverse Linked List
- 206. Reverse Linked List
- 206. Reverse Linked List
- 206. Reverse Linked List
- 206. Reverse Linked List
- 206. Reverse Linked List
- 206. Reverse Linked List
- 206. Reverse Linked List
- 206. Reverse Linked List
- 206. Reverse Linked List
- 206. Reverse Linked List
- 206. Reverse (Linked List)
- 如何理解android中的Context?
- 调用微信JS-SDK接口上传图片
- 跟着郝斌学数据结构(10)——链式二叉树
- Maven日常 —— 你应该知道的一二三
- Linux中环境变量文件及配置
- 206. Reverse (Linked List)
- WIN10下JLINK V8 固件烧录出现问题记录
- Python装饰器模式学习总结
- Hive几种参数配置方法
- 众包物流:把每个人变成快递员
- 蓝桥杯 历届试题 排列序数
- 设计模式之三抽象工厂模式
- 让内层Div将外层Div撑开
- 防止DIV被撑开的CSS