1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| #include<iostream> using namespace std;
struct node { int data; node* next; };
node *create() { node *head; head = (node *)malloc(sizeof(node)); head->next=NULL; head->data =0; node *p = head; cout<<"Please input all the data and end with '-1': "<<endl; int x; node *s; while (cin>>x) { if (-1 != x) { s = (node *)malloc(sizeof(node)); s->data = x; p->next =s; p = s; head->data++; } else { break; } } p->next =NULL; return head; }
void print(node* head) { if(NULL == head || NULL == head->next) { cout<<"链表为空"<<endl; } node* temp = head->next; while(temp != NULL) { cout<<temp->data<<" "; temp = temp->next; } cout<<endl; }
node *reverse(node *head) { node *p1, *p2, *p3; if (NULL == head || NULL == head->next) { cout<<"链表为空"<<endl; return head; } p1 = head->next; p2 = p1->next; p1->next = NULL; while (NULL != p2) { p3 = p2->next; p2->next = p1; p1 = p2; p2 = p3; } head->next = p1; return head; } int main() { node* list = create(); print(list); reverse(list); print(list); system("pause"); return 0; }
|