其他分享
首页 > 其他分享> > 反转单链表

反转单链表

作者:互联网

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

点击查看代码

#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;
}

标签:Node,pre,head,单链,反转,next,current,NULL
来源: https://www.cnblogs.com/arivin/p/16247713.html