数组法(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;
}
}
文章介绍了如何使用C++和Java分别通过数组法、迭代法和递归法来反转链表。数组法虽然直观但空间消耗大;迭代法利用指针操作实现,代码简洁;递归法展示了通过调用自身处理子问题的过程。
761

被折叠的 条评论
为什么被折叠?



