力扣206反转链表(迭代)

力扣206反转链表(迭代)

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

迭代

  • 定义两个指针: prev 和 curr ;prev 在前 curr 在后。
  • 每次让 prev 的 next 指向 curr ,实现一次局部反转
  • 局部反转完成之后,prev 和 curr 同时往前移动一个位置
  • 循环上述过程,直至 prev 到达链表尾部
//
//  main.cpp
//  206ReverLinkedList
//
//  Created by MXQ on 2020/10/27.
//

#include <iostream>
using namespace std;
 // 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==nullptr || head->next==nullptr) {
            return head;
        }
        ListNode* result=head;
        ListNode* prev;
        ListNode* curr;
        prev=head;
        curr=prev->next;
        while (curr!=nullptr) {
            prev->next=curr->next;
            curr->next=result;
            result=curr;
            curr=prev->next;
        }
        return result;
    }
};
int main(int argc, const char * argv[]) {
    // insert code here...
    ListNode head[5]={1,2,3,4,5};
    head[0].next=&head[1];
    head[1].next=&head[2];
    head[2].next=&head[3];
    head[3].next=&head[4];
    ListNode* p=head;
    while (p!=nullptr) {
        cout<<p->val<<" ";
        p=p->next;
    }
    cout<<endl;
    Solution s;
    auto result=s.reverseList(head);
    ListNode* q=result;
    while (q!=nullptr) {
        cout<<q->val<<" ";
        q=q->next;
    }
    cout<<endl;
    std::cout << "Hello, World!\n";
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值