反轉鏈表

題目描述:將鏈表進行反轉

代碼如下:

<pre name="code" class="cpp"><span style="font-size:14px;">#include<iostream>
#include<vector>
using namespace std;

//鏈表創建
struct ListNode{
	int val;
	ListNode*next;
	ListNode(int x) :val(x), next(NULL){}
};

class Solution{
public:
	//鏈表反轉函數
	ListNode* ReverseList(ListNode* head){
		if (head == NULL || head->next == NULL)
			return head;
		//創建last作爲head的下一個節點
		ListNode* last = new ListNode(NULL);
		//一定要主要,head的下一個節點爲空
		last = head->next;
		head->next = NULL;
		ListNode* mid = new ListNode(NULL);
		while (last){
			mid = last->next;
			last->next = head;
			//頭節點時已經反轉鏈表的頭節點
			head = last;
			last = mid;
		}
		return head;
	}
};

//測試代碼
int main(){
	//創建鏈表
	ListNode* head = new ListNode(NULL);
	ListNode* head1 = new ListNode(NULL);
	int val;
	cout << "創建鏈表: ";
	while (cin >> val&&val){
		//如果頭節點爲空
		if (head->val == NULL){
			head->val = val;
			head1 = head;
		}
		//如果頭節點不爲空
		else
		{
			ListNode* head2 = new ListNode(val);
			head1->next = head2;
			head1 = head1->next;
		}
	}
	//尾節點下一個節點爲空
	head1->next = NULL;

	//輸出反轉的鏈表
	Solution solution;
	ListNode* head3 = solution.ReverseList(head);
	cout <<endl<<"------------------------"<<endl<<endl<< "反轉的鏈表輸出爲: ";
	while (head3 != NULL){
		cout << head3->val << " ";
		head3 = head3->next;
	}
	cout << endl;
	system("pause");
	return 0;
}</span>



測試結果如下:





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章