LeetCode - 反转链表 - 初级算法

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL 进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

很简单的 说

/**
 * 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 * lastP = NULL;
        ListNode * currentP = head;
        ListNode * forNowNextP = head -> next;
        
        while(currentP != NULL){
            forNowNextP = currentP -> next;
            currentP -> next = lastP;
            lastP = currentP;
            currentP = forNowNextP;
        }
        
        return lastP;
    }
};

就像 是 交换两个变量的 操作一样
联想一下变量交换操作就解决了

猜你喜欢

转载自blog.csdn.net/weixin_39722329/article/details/83351044