AcWing 35. 反转链表(C++)- 链表

题目链接:https://www.acwing.com/problem/content/33/
题目如下:
在这里插入图片描述

/**
 * 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* pre=NULL,*cur=head;
        
        while(cur!=NULL){
    
    
            ListNode* next=cur->next;//保存cur的下一个节点,因为接下来要改变cur-》next
            cur->next=pre;//反转操作
            
            pre=cur;//更新pre和cur指针
            cur=next;
        }
        
        return pre;//pre是反转后的头节点
    }
};

在这里插入图片描述

/**
 * 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) {
    
    
        //方法二:递归
        if(head==NULL||head->next==NULL) return head;//防止空链表及只有一个节点的链表
        
        auto next=reverseList(head->next);
        head->next->next=head;
        head->next=NULL;
        
        return next;
    }
};

Guess you like

Origin blog.csdn.net/qq_40467670/article/details/121109588