微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

反转单链表

思路:三个指针实现原地反转,不懂的看代码

点击查看代码

#include <iostream>
using namespace std;

//博客园有时候不常看消息,有相关代码疑问的可以联系我,请注明来意,wx:A470216705

struct Node {
    Node* next;
    int value;
};

Node* linkList_inversion(Node* head)
{
    if (head == NULL)
        return NULL;
    Node* behind = NULL;
    Node* current = head;
    Node* pre = head->next;

    while (current != NULL)
    {
        current->next = behind;
        behind = current;
        current = pre;
        if(pre != NULL)
            pre = pre->next;
    }
    return behind;

}

void print_list(Node* head)
{
    Node* p = head;
    while (p != NULL)
    {
        cout << p->value<<"  ";
        p = p->next;
    }
    cout << endl;
}

int main()
{
    Node* head = new Node;
    head->next = NULL;
    head->value = 2;

    Node* p1 = new  Node;
    head->next = p1;
    p1->value = 87;

    Node* p2 = new  Node;
    p1->next = p2;
    p2->value = 43;


    Node* p3 = new  Node;
    p2->next = p3;
    p3->value = 43;
    p3->next = NULL;

    print_list(head);
   
    Node* new_head = linkList_inversion(head);
    print_list(new_head);
   
    return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐