天天看點

LeetCode206(反轉連結清單)

菜鳥成長逆襲之旅,愛好撸鐵和撸代碼,有強制的限制力,希望通過自己的努力做一個高品質人

Work together and make progress together

反轉連結清單

反轉一個單連結清單。

示例:

輸入: 1->2->3->4->5->NULL

輸出: 5->4->3->2->1->NULL

進階:

你可以疊代或遞歸地反轉連結清單。你能否用兩種方法解決這道題?

/**
 * 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 *newHead = NULL;
		while(head){
			ListNode *t = head->next;
			head->next = newHead;
			newHead = head;
			head = t;
		}
        return newHead;
    }
};


 * 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 *newHead = NULL;
		while(head){
			ListNode *t = head->next;
			head->next = newHead;
			newHead = head;
			head = t;
		}
        return newHead;
    }
};