20170514_单链表的构造与逆置
//148. Sort List
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include<iostream>
#include<vector>
using namespace std;
//单链表节点
struct ListNode
{
int val;
ListNode *next;
ListNode(int x):val(x),next(NULL) {}
};
//尾插法建立一个单链表
ListNode *CreatList(ListNode * &root, vector<int> &a)
{
int n=a.size();
if(n==0)
return root;
else
{
root=new ListNode(a[0]);
ListNode *r=root;
for(int i=1; i<n; ++i)
{
ListNode *s=new ListNode(a[i]);
r->next=s;
r=s;
}
return root;
}
}
//顺序输出一个单链表
void OutList(ListNode *root)
{
ListNode *p=root;
while(p!=NULL)
{
if(p->next!=NULL)
cout<<p->val<<",";
else
cout<<p->val;
p=p->next;
}
cout<<endl;
}
//单链表逆置
ListNode *ConvertList(ListNode *root)
{
if(root==NULL || root->next==NULL)
return root;
else
{
ListNode *pcur=root;
ListNode *qnext=pcur->next;
pcur->next=NULL;
while(qnext!=NULL)
{
root=qnext;
ListNode *qq=qnext->next;
qnext->next=pcur;
pcur=qnext;
qnext=qq;
}
return root;
}
}
class Solution
{
public:
ListNode *sortList(ListNode *head)
{
;
}
};
int main()
{
vector<int> a;
int ch;
cout<<"依次输入单链表节点数据:"<<endl;
while(cin>>ch)
a.push_back(ch);
ListNode *r;
ListNode *root=CreatList(r,a);
cout<<"单链表建立完成."<<endl;
cout<<"顺序输出单链表:"<<endl;
OutList(root);
cout<<"顺序输出单链表完成."<<endl;
cout<<"逆置该单链表:"<<endl;
ListNode *root2=ConvertList(root);
cout<<"输出逆置后的单链表:"<<endl;
OutList(root2);
cout<<"逆置后的单链表输出完成."<<endl;
system("pause");
return 0;
}