数组法(C++)
遍历链表,把结点的值存储在vector中,然后重新创建链表。
缺点:大量空间浪费
class Solution {
public:
ListNode* reverseList(ListNode* head) {
vector<int> nums;
ListNode* p = head;
while(p != nullptr) {
nums.push_back(p->val);
p = p->next;
}
ListNode* rhead = new ListNode();
p = rhead;
for(int i=nums.size()-1; i>=0; i--) {
ListNode* temp = new ListNode(nums[i]);
p->next = temp;
p = temp;
}
return rhead->next;
}
};
迭代法(Java)
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null) return null;
ListNode t1 = null;
ListNode t2 = head;
ListNode temp;
while(t2!=null) {
temp = t2.next;//她的位置
t2.next = t1;
t1=t2;
t2=temp;
}
return t1;
}
}
递归法
这里是官网的示范,
看不懂!!
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}