重排链表
来源:互联网 发布:apache spark 版本 编辑:程序博客网 时间:2024/05/20 02:28
给定一个单链表L: L0→L1→…→Ln-1→Ln,
重新排列后为:L0→Ln→L1→Ln-1→L2→Ln-2→…
必须在不改变节点值的情况下进行原地操作。
class Solution {public: /** * @param head: The first node of linked list. * @return: void */ void reorderList(ListNode *head) { // write your code here if(head == NULL){head = NULL;} else{ ListNode *mid = getmid(head); ListNode *se = mid->next; mid->next = NULL; ListNode *fr = head; ListNode *rese = reverse(se); head = merge(fr,rese); } } ListNode *reverse(ListNode *head){ ListNode *prev = NULL; while(head != NULL) { ListNode *temp = head->next; head->next = prev; prev = head; head = temp; } return prev; } ListNode *merge(ListNode *a,ListNode *b){ ListNode *dummy = new ListNode(0); ListNode *p = dummy; while(a != NULL && b != NULL){ p->next = a; a = a->next; p = p->next; p->next = b; b = b->next; p = p->next; } if(b != NULL){ p = b; } return dummy->next; } ListNode *getmid(ListNode *head){ ListNode *fast = head->next; ListNode *slow = head; while(fast != NULL && fast->next != NULL && fast->next->next != NULL){ fast = fast->next->next; slow = slow->next; } return slow; }};
注意点:1. reorder list这个函数没有返回值,因此使用if语句判断head是否等于NULL,后面的情况要用else语句。
0 0
- 重排链表
- 重排链表
- 重排链表
- 重排链表
- LintCode:重排链表
- LintCode : 重排链表
- 重排链表
- 重排链表
- 重排链表-LintCode
- Reorder List 重排链表
- 算法:链表的重排
- Reorder List 链表重排
- L2-022. 重排链表
- lintcode(99)重排链表
- L2-022. 重排链表
- L2-022. 重排链表
- Java实现-重排链表
- L2-022. 重排链表
- 单片机轻松入门之一点亮一个发光二极管
- Gallery实现图片文字左右滑动放大当前选中
- python核心编程-线程threading模块之生产者与消费者
- 类
- 【Android】获取控件的宽和高
- 重排链表
- 1.1 Git的本地使用详解
- Spark 阶段总结 2
- Document对象的使用:getElementById()和getElementsByTagName()方法的使用练习
- .PHONY makefile中的伪目标
- 装ghost遇到的问题之一“Windows failed to start. A Recent hardware or software change might be the cause.”
- Android开发套路收集整理与讨论
- 分别用DOM方式和jQuery方式判断复选框是否被选中
- Makefile有三个非常有用的变量。分别是$@,$^,$<代表的意义分别是: