#include <iostream>
using namespace std;

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

struct node *head;

void insert(struct node * &head,int value)
{
    if(head == NULL)
    {
        head = new struct node;
        head->value = value;
        head->next = NULL;
        return;
    }

    struct node *p = new struct node;
    p->value = value;
    p->next = NULL;

    struct node *q = head;
    while(q->next != NULL)
    {
        q = q->next;
    }

    q->next = p;

}

void print(struct node *head)
{
    struct node *p = head;
    while(p != NULL)
    {
        cout<<p->value<<"  ";
        p = p->next;
    }
}
void reverse(struct node * &head)
{

    if(head == NULL || head->next == NULL)
        return;
    struct node *p = head;
    struct node *q = head->next;

    while(q != NULL)
    {
        struct node *next = q->next;
        q->next = p;
        p = q;
        q = next;
    }
    head->next = NULL;
    head = p;
}

int main()
{
    head = NULL;

    insert(head,1);
    insert(head,3);
    insert(head,5);
    insert(head,9);
    insert(head,11);
    insert(head,16);
    insert(head,18);
    insert(head,6);
    insert(head,10);
    insert(head,12);
    insert(head,13);
    insert(head,15);
    cout<<"链表:";
    print(head);
    cout<<endl<<"逆序后为:"<<endl;
    reverse(head);
    print(head);
    cout<<endl;

    return 0;
}

 还可以使用递归实现

//递归实现
struct node *reverse2(struct node *head)
{
    if(head == NULL || head->next == NULL)
        return head;

    struct node *p;
    struct node *next = head->next;
    p = reverse2(next);
    next->next = head;
    head->next = NULL;
    return p;
}

 

相关文章:

  • 2021-11-29
  • 2021-09-19
  • 2022-12-23
  • 2022-12-23
  • 2021-10-25
  • 2022-12-23
  • 2021-02-17
猜你喜欢
  • 2021-07-08
  • 2022-12-23
  • 2021-08-23
  • 2022-01-19
  • 2021-10-29
  • 2022-02-16
相关资源
相似解决方案