实现一单链表的逆置,并输出逆置前后的结果。。。
写的简单一点,参考写法: #include<iostream> using namespace std; typedef struct list { int data; struct list *next; ;}LIST; LIST * creat()//创建链表 { LIST *head,*p; int flag=1,d; head = new LIST; p = head; cout<<"输入数据\n"; cin>>d; head ->data = d; while(flag) { LIST *tem = new LIST; cout<<"输入数据\n"; cin>>d; if(0!=d)//输入0结束 { tem->data = d; p->next = tem; p = tem; } else flag = 0; } p->next = NULL; return head; } LIST *reverse(LIST *head)//链表逆置 { if(head == NULL ||head->next ==NULL) return head; LIST *p1,*p2,*p3; p1 = head; p2 = head->next; while(p2) { p3 = p2->next; p2->next = p1; p1 = p2; p2 = p3; } head->next = NULL; head = p1; return head; } void Delete(LIST *h)//销毁链表 { while(h!=NULL) { LIST *p = h; h=h->next; delete p; } } void show(LIST *head)//打印链表 { if(head == NULL) cout<<"链表为空\n"; while(head != NULL) { cout<<head->data<<" "; head = head->next; } cout<<endl; } int main() { LIST *head; head = creat(); cout<<"链表元素为:\n"; show(head); cout<<"链表逆置后的为:\n"; head = reverse(head); show(head); Delete(head); return 0; }