反轉鏈表

	/*
反轉一個單鏈表。

進階:
鏈表可以迭代或遞歸地反轉。你能否兩個都實現一遍?
**/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
//就地逆置法
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *new_head=NULL;//指向新鏈表頭結點的指針
		while(head){
		ListNode *next=head->next;//備份head->next
		head->next=new_head;//更新head->next
		new_head=head;//移動new_head
		head=next;//遍歷鏈表
    }
	return new_head;//返回新鏈表頭結點
};

//頭插法
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
		ListNode temp_head(0);
		while(head){
			ListNode *next=head->next;
			head->next=temp_head.next;
			temp_head.next=head;
			head=next;
		}
		return temp_head.next;
	}
};
//比較
1、
	ListNode temp_head(0);//臨時節點
	ListNode *new_head=NULL;//指針變量




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