反转链表

来源:互联网 发布:南风知我意晋江书包网 编辑:程序博客网 时间:2024/06/03 06:45

定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。

#include <iostream>#include <string.h>#include <stdlib.h>using namespace std;struct Node{int data;struct Node* next;};struct Node* create_list(int len){if (len <= 0)return NULL;struct Node* head;struct Node* tmp;struct Node* pre;for (int i=0; i<len; i++){if (i == 0){head = tmp = new struct Node;tmp->data = i;tmp->next = NULL;pre = tmp;continue;}tmp = new struct Node;tmp->data = i;tmp->next = NULL;pre->next = tmp;pre = tmp;}return head;}void visit(const struct Node *head){        if (head == NULL)            return;        const struct Node *tmp;        tmp = head;        while (tmp)        {            cout << tmp->data << endl;            tmp = tmp->next;        }}struct Node* reverse(struct Node *head){if (head == NULL)return NULL;struct Node *nex = NULL;struct Node *tmp = NULL;struct Node *pre = NULL;tmp = head;while (1){if (pre == NULL) // first{pre = tmp;nex = tmp->next;tmp = tmp->next;pre->next = NULL;continue;}nex = tmp->next;if (nex == NULL){tmp->next = pre;return tmp;}tmp->next = pre;pre = tmp;tmp = nex;}}void free_list(struct Node *head){if (head == NULL)return;struct Node *tmp;while (head){tmp = head;head = head->next;delete tmp;}}int main(){struct Node *head = create_list(5);visit(head);cout << endl;head = reverse(head);visit(head);free_list(head);return 0;}



0 0
原创粉丝点击