c_cpp 反转链表

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 反转链表相关的知识,希望对你有一定的参考价值。

#include <bits/stdc++.h>
using namespace std;

struct linked_list {
    int data;
    struct linked_list* next;
};
typedef struct linked_list node;

void print(node* head) {
    node* n = head;
    while (n != NULL) {
        cout<< n->data << "->";
        n = n->next;
    }
    cout<< "\n";
}

node* insert (node* head, int n) {
    node* list = (node*)malloc(sizeof(node*));
    list->data=n;
    list->next=head;
    head=list;
    return head;
}

node* reverse(node* head) {
    node *prev=NULL,*current = head, *next=NULL;
    while (current!=NULL) {
        next = current->next;
        current->next = prev;
        prev = current;
        current=next;
    }
    head = prev;
    return head;
}

int main () {
    int n;
    node* head=NULL;
    while (true) {
        cout<< "Enter the element, enter -9 to stop: ";
        cin>>n;
        if (n==-9)
            break;
        else
            head = insert(head,n);
    }
    print(head);
    head = reverse(head);
    print(head);
}

以上是关于c_cpp 反转链表的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 仅使用2个指针迭代地反转链表(一种有趣的方法)

c_cpp 字符串反转

c_cpp 反转方程式

c_cpp 反转阵列

c_cpp 226.反转二叉树

c_cpp Zlib函数:位反转