Leetcoder Reorder List

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→Ln-1→L2→Ln-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}.

 

class Solution {
public:
	vector<void*> addr;

	void reorderList(ListNode* head) {
		if (head == NULL)return;
		ListNode* begin = head;
		//将所有的地址压入vector
		while (begin != NULL)
		{
			addr.push_back(begin);
			begin = begin->next;
		}
		//向量的 左右两边
		int l = 1;
		int r = addr.size() - 1;

		ListNode* cur = head;
		while (l < r)
		{
			cur->next = ((ListNode*)addr[r]);
			cur = cur->next;
			cur->next = ((ListNode*)addr[l]);
			cur = cur->next;
			l++;
			r--;
		}

		if (l == r)
		{
			cur->next = ((ListNode*)addr[l]);
		    cur = cur->next;
		}

		cur->next = NULL;



	}
};

  

posted @ 2017-05-04 14:46  风轻云淡走天涯  阅读(132)  评论(0编辑  收藏  举报