leetcode 206. 反转链表

 #思路

 

# 思路:定义一个当前节点,赋值为head,定义一个pre作为反转后的第一个节点,定义一个临时node 存放当前节点的下一个节点
/**
 * 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* current = head;
        ListNode* pre = NULL;
        while(current!=NULL)
        {
            ListNode*temp = current->next; // 定义一个指针专门保存current的下一个节点
            current->next = pre;//将第一个指针指向前面一个
            pre = current;//指针滑动直到current为空为止
            current =temp;
        }
        return pre;

    }
};

代码2:

/**
 * 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)
        {
            return NULL;
        }
        ListNode *pre = NULL;
        ListNode *next = NULL;
        while(head!=NULL)
        {
            next = head->next; //获得下一个节点
            head->next = pre;//将前一个节点附在后面
            pre = head;//交换节点
            head = next;
        }
        return 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;
        }
        ListNode *pre = reverseList(head->next); //递归解法
        head->next->next = head;
        head->next = NULL;
        return pre;
    }
};

 

posted @ 2021-09-26 15:33  A-inspire  Views(20)  Comments(0Edit  收藏  举报