单链表逆转

来源:互联网 发布:韩国人化妆品知乎 编辑:程序博客网 时间:2024/05/02 15:52
#include <iostream>using namespace std;typedef struct NODE{int data;NODE *next;}node;//create a list.node *create(){node *head, *first, *second;head = new(node);first = head;int num;cout << "Now input the list:\n";while(cin >> num && num){cout << "number:" << num << endl;second = new(node);second->data = num;first->next = second;second->next = NULL;first = second;}if(first - head == 0)return NULL;head = head->next;return head;}//reverse a list.node *reverse(node* head) {if(head == NULL || head->next == NULL)return NULL;node *pre, *cur, *ne;pre=head;cur=head->next;while(cur){ne = cur->next;cur->next = pre;pre = cur;cur = ne;}head->next = NULL;head = pre;return head;}//打印链表.void printList(node *head){cout << "Now output the list:\n";//list is null.if(head == NULL)return ;//list is not null.else{node *p = head;while(p != NULL){cout << p->data << " ";p = p->next;}cout << endl;}}int main(){node *p = create();printList(p);p = reverse(p);printList(p);return 0;}

原创粉丝点击