首页 > 其他 > 详细

LeetCode之Reorder List

时间:2014-03-22 10:10:22      阅读:409      评论:0      收藏:0      [点我收藏+]

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…

You must do this in-place without altering the nodes‘ values.

For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
   	void reorderList(ListNode *head) {
		ListNode *p, *q;
		p = head, q = head;
		if (head == NULL||head->next==NULL||head->next->next==NULL) return;
		//find the mid
		while (q&&q->next&&q->next->next){
			q = q->next->next;
			p = p->next;
		}
		q=p->next;
		p->next=NULL;
		reverseList(q);
		mergeList(head, q);
	}
	void reverseList(ListNode *&head) {
		ListNode *p, *q;
		p = head, q =NULL;
		if (head == NULL) return;
		while (p->next){
			q = p->next;
			p->next = q->next;
			q->next = head;
			head = q;
		}
	}
	void mergeList(ListNode *list_1, ListNode *list_2) {
		ListNode *p, *q,*tmp;
		p = list_1, q = list_2;
		while (q){
			tmp = q->next;
			q->next = p->next;
			p->next = q;
			p = q->next;
			q = tmp;
		}
	}
};


LeetCode之Reorder List,布布扣,bubuko.com

LeetCode之Reorder List

原文:http://blog.csdn.net/smileteo/article/details/21758759

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!