[LeetCode] 206. 反转链表(Reverse Linked List)

本文已收录于 LeetCode刷题 系列,共计 28 篇,本篇是第 10 篇

本文已收录到:LeetCode刷题 专题

[title]题目[/title]

反转一个单链表。

示例:

输入:

 1->2->3->4->5->NULL

输出:

 5->4->3->2->1->NULL

[title]视频讲解[/title]

[bilibili cid=”” page=”1″]710133752[/bilibili]

 

[title]代码[/title]

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. ListNode* reverseList(ListNode* head) {
  12. ListNode* pre = nullptr;
  13. ListNode* cur = nullptr;
  14. ListNode* temp = head;
  15. while (temp != nullptr)
  16. {
  17. pre = cur;
  18. cur = temp;
  19. temp = cur->next;
  20. cur->next = pre;
  21. }
  22. return cur;
  23. }
  24. };
/**
 * 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 = nullptr;
        ListNode* temp = head;

        while (temp != nullptr)
        {
            pre = cur;
            cur = temp;
            temp = cur->next;
            cur->next = pre;
        }
        return cur;
    }
};

 

作者: 高志远

高志远,24岁,男生

发表评论

邮箱地址不会被公开。