Reverse a singly linked list.
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
反轉一個單向的串列鏈結。
進階:
一個串列鏈結可以用迭代或是遞迴實作,你可以兩種都實作嗎?
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
next
設為前一個,接著把三個點都往下移。重複至到尾巴(NULL
)。next
往回設,將自己的點的next
設為NULL
。然後用遞迴從後面開始往回做。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head || !head->next) return head;
ListNode* next = head->next;
ListNode* newHead = head;
ListNode* pre = NULL;
while(next)
{
pre = newHead;
newHead = next;
next = newHead->next;
newHead->next = pre;
}
head->next = NULL;
return newHead;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head || !head->next) return head;
ListNode* n = head->next;
n = reverseList(n);
head->next->next = head;
head->next = NULL;
return n;
}
};
LeetCode
C++
1. Two Sum
Nov 15, 2023You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:
Nov 15, 2023Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.
Nov 9, 2023There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.
Nov 9, 2023or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up