国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

leecode 解題總結:143. Reorder List

2019-11-08 02:46:37
字體:
來源:轉載
供稿:網友
#include <iostream>#include <stdio.h>#include <vector>#include <string>using namespace std;/*問題:Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorder it to: L0→Ln→L1→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}.分析:此題就是要將最后面的結點插在第一個結點后面,倒數第二個結點插在第二個結點后面且不允許修改結點的值。如果不允許修改結點的值,那么肯定要找到末尾結點,末尾結點的前面結點這些。也就是要找到一個結點前面結點情況用一個數組A存儲所有結點不就行了,設長度為n然后A[0]指向A[n-1],A[n-1]指向A[1],A[1]指向A[n-2]只需要遍歷到len/2的結點,比如1 2 3 4 5,那么變成1 5 2 4 3輸入:1(數組元素個數)121 24 1 2 3 451 2 3 4 5輸出11 21 4 2 31 5 2 4 3*/struct ListNode {     int val;     ListNode *next;     ListNode(int x) : val(x), next(NULL) {}};class Solution {public:    void reorderList(ListNode* head) {        if(!head)		{			return;		}		vector<ListNode*> nodes;		ListNode* node = head;		while(node)		{			nodes.push_back(node);			node = node->next;		}		if(nodes.empty())		{			return ;		}		int size = nodes.size();		//設置結點指向		ListNode* nextNode = NULL;		for(int i = 0 ; i < size / 2 ; i++)		{			if(i + 1 < size)			{				nextNode = nodes.at(i+1);			}			else			{				nextNode = NULL;			}			nodes.at(i)->next = nodes.at(size - i - 1);			//當前結點不是和下一個結點相同,才指向			if(nodes.at(size - i - 1) != nextNode)			{				nodes.at(size - i - 1)->next = nextNode;			}			else			{				nodes.at(size - i - 1)->next = NULL;			}		}		//這里最后一個結點要設置為空		//size/2是最后結點,這個元素是沒有交換的		nodes.at(size/2)->next = NULL;    }};void PRint(ListNode* head){	if(!head)	{		cout << "no result" << endl;	}	ListNode* tempHead = head;	while(head)	{		cout << head->val << " ";		head = head->next;	}	cout << endl;	head = tempHead;}ListNode* buildList(vector<int>& nums){	if(nums.empty())	{		return NULL;	}	int size = nums.size();	ListNode* head ;	ListNode *tail;	ListNode* node;	for(int i = 0 ; i < size ; i++)	{		if(i)		{			node = new ListNode(nums.at(i));			tail->next = node;			tail = node;		}		else		{			head = new ListNode(nums.at(i));			tail = head;		}	}	return head;}void deleteList(ListNode* head){	ListNode* node;	while(head)	{		node = head->next;		delete head;		head = node;	}}void process(){	 vector<int> nums;	 int value;	 int num;	 Solution solution;	 vector<int> result;	 while(cin >> num )	 {		 nums.clear();		 for(int i = 0 ; i < num ; i++)		 {			 cin >> value;			 nums.push_back(value);		 }		 ListNode* head = buildList(nums);		 solution.reorderList(head);		 print(head);		 deleteList(head);//刪除節點了	 }}int main(int argc , char* argv[]){	process();	getchar();	return 0;}
上一篇:基礎練習 FJ的字符串

下一篇:Crackme 20

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 融水| 桓台县| 屏边| 元氏县| 青海省| 淮阳县| 林西县| 洛阳市| 砚山县| 西昌市| 崇文区| 汽车| 茂名市| 阿拉善盟| 察隅县| 方正县| 遂川县| 宜君县| 长阳| 轮台县| 阿图什市| 吴忠市| 泰安市| 延长县| 息烽县| 绿春县| 余江县| 凤台县| 阳高县| 县级市| 丹巴县| 万载县| 玉环县| 突泉县| 南丰县| 新巴尔虎右旗| 太仆寺旗| 秦安县| 称多县| 营山县| 宁远县|