程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> c++-有序單鏈表的實現 C++

c++-有序單鏈表的實現 C++

編輯:編程綜合問答
有序單鏈表的實現 C++

#include
using namespace std;
struct Node
{ int data;
Node *next;
};
void insert(Node *&head,int num)
{ Node *s,*p,*q;
s=new Node;
s->data=num;
s->next=NULL;
if(head==NULL)
{ head=s;
return;
}
if(head->data>s->data)
{ s->next=head;
head=s;
return;
}
for(q=head,p=head->next;p;q=p,p=p->next)
if(p->data>s->data)
{ s->next=p;
q->next=s;
return;
}
q->next=s;
return;
}
void ShowNode( Node *head)
{cout<<"now the items of list are:";
while(head)
{ cout<data<<" ";
head=head->next;}
cout< }
void ReverseList(Node *head)
{ cout Node *s,*p,*q;
if(head==NULL||head->next==NULL)
{return;}
s=head->next;
p=s->next;
s->next=NULL;
while(p)
{q=s->next;
p->next=s;
s=p;
p=q;
head->next=s;
cout<data<<" ";
head=head->next;
}cout< }
int main()
{ int k;
Node *head=NULL;
cin>>k;
while(k!=0)
{insert(head,k);
cin>>k;}
ShowNode(head);
ReverseList(head);
}

這是我的代碼,有序輸出可以用,但逆序輸出元素就不成功。求大神,教改程序。

最佳回答:


http://codepad.org/uXUnowLl

 #include<iostream>
using namespace std;
struct Node
{ int data;
  Node *next;
};
void insert(Node *&head,int num)
{ Node *s,*p,*q;
  s=new Node;
  s->data=num;
  s->next=NULL;
  if(head==NULL)
  { head=s;
    return;
  }
  if(head->data>s->data)
  { s->next=head;
    head=s;
    return;
  }
  for(q=head,p=head->next;p;q=p,p=p->next)
   if(p->data>s->data)
   { s->next=p;
     q->next=s;
     return;
   }
   q->next=s;
   return;
}
void ShowNode( Node *head)
{cout<<"now the items of list are:";
 while(head)
 { cout<<head->data<<" ";
   head=head->next;}
   cout<<endl;
}
void ReverseList1(Node *head1)
{
if (head1->next != NULL)
ReverseList1(head1->next);
cout<<head1->data<<" ";
}
void ReverseList(Node *head)
{ cout<<"now the change items of list are:";
/*    Node *s,*p,*q;
 if(head==NULL||head->next==NULL)
  {return;}
  s=head->next;
  p=s->next;
  s->next=NULL;
  while(p)
  {q=s->next;
    p->next=s;
    s=p;
    p=q;
    head->next=s;
cout<<head->data<<" ";
   head=head->next;
   }cout<<endl;
*/
ReverseList1(head);
}


int main()
{ int k;
  Node *head=NULL;
for (k=1; k <= 5; k++)
    insert(head,k);
ShowNode(head);
ReverseList(head);
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved