C++编程实现单链表的逆置

来源:互联网 发布:我欲封天灵珠升阶数据 编辑:程序博客网 时间:2024/06/04 18:55

实现一单链表的逆置,并输出逆置前后的结果。。。

写的简单一点,参考写法:#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;}

0 0
原创粉丝点击