LeetCode Reorder List

链接: https://oj.leetcode.com/problems/reorder-list/


空间复杂度为O(n),时间复杂度为 O(n)的代码:


/**
 * 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)
		{
			vector<ListNode *> list;	
			ListNode *tem=head;
			if(head==NULL)
			    return;
			while(tem)
			{
				list.push_back(tem);
				tem=tem->next;
			}
			int i=0,j=list.size()-1;
			while(i+1<j)
			{
				ListNode *s1=list[i];
				ListNode *s2=list[j];
				s2->next=(s1)->next;
			
				(s1)->next=s2;
				i++;
				j--;
			}
			list[j]->next=NULL;
		}
};


你可能感兴趣的:(LeetCode)