leetcode(剑指offer 24)-反转链表C++实现

2021/7/2 1:21:20

本文主要是介绍leetcode(剑指offer 24)-反转链表C++实现,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

剑指 Offer 24. 反转链表 - 力扣(LeetCode) (leetcode-cn.com)

 

/**
 * 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=nullptr;
        ListNode* cur=head;
        while(cur)
        {
            ListNode* nextnode=cur->next;
            cur->next=pre;
            pre=cur;
            cur=nextnode;
        }
        return pre;


        // if(head==NULL) return NULL;
        // if(head->next == NULL) return head;
        // ListNode* last = reverseList(head->next);
        // head->next->next = head;
        // head->next = NULL;
        // return last;
    }
};

  

注释掉的是递归写法



这篇关于leetcode(剑指offer 24)-反转链表C++实现的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程