数据结构与算法之链表反转

思路一:原始链表从表尾插入新元素,反转链表从表头插入新元素,见下面代码的函数reverse;

思路二:原地反转,当前节点的next指向下个节点的next,下个节点放在当前表头,见下面代码的函数reverse2。


show you my code:

#include <iostream>

using namespace std;

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

Node* create(Node* head, int* data, size_t length);
Node* insert(Node* head, int value);
void print(Node* head);
Node* reverse(Node* head);
Node* insertFromHead(Node* head, int value);
Node* reverse2(Node* head);

int main(int argc, char *agrv[])
{
    const size_t length = 10;
    int data[length];
    for(size_t i = 0 ; i < length ; i ++)
      data[i] = i;
    Node* head = NULL;
    head = create(head, data, length);
    print(head);
    head = reverse2(head);
    print(head);

    return 0;
}

Node* create(Node* head, int* data, size_t length)
{
    for(int i = 0; i < length; i ++)
    {
        head = insert(head, data[i]);
    }
    return head;
}

Node* insert(Node* head, int value)
{
    if(!head)
    {
        head = new Node;
        head->key = value;
        head->next = NULL;
    }
    else
    {
        Node* now = NULL;
        for(now = head; now->next != NULL; now = now->next)
        {

        }
        Node* newNode = new Node;
        newNode->key = value;
        newNode->next = NULL;
        now->next = newNode;
    }

    return head;
}

void print(Node* head)
{
    for(Node* now = head; now != NULL; now = now->next)
    {
        cout<<now->key<<"@"<<(int)now<<" and next @"<<(int)now->next<<endl;
    }
    cout<<endl;
}

Node* reverse(Node* head)
{
    Node* newHead = NULL;
    for(Node* now = head; now != NULL; now = now->next)
    {
        newHead = insertFromHead(newHead, now->key);
    }

    return newHead;
}

Node* insertFromHead(Node* head, int value)
{
    if(!head)
    {
        head = new Node;
        head->key = value;
        head->next = NULL;
    }
    else
    {
        Node* newNode = new Node;
        newNode->key = value;
        newNode->next = head;
        head = newNode;
    }

    return head;
}

Node* reverse2(Node* head)
{
    Node* tmp = NULL;
    for(Node* now = head ; now->next != NULL ;)
    {
        tmp = now->next;
        now->next = now->next->next;
        tmp->next = head;
        head = tmp;
    }

    return head;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值