关于输出有序链表的问题,从小到大依次建立1个带头结点,用c++的方法解决,会的给给思路
建表的时候,根据数据的大小查找插入的位置,调整前后两个节点的next指针即可。
如下:
#include <iostream>
using namespace std;
typedef struct _node
{
int data;
struct _node* next;
}LinkNode;
//插入链表
LinkNode* insertlist(LinkNode* head,LinkNode* t)
{
LinkNode* p,*front;
front = head;
p = front->next;
while(p && p->data < t->data)
{
front = p;
p = p->next;
}
if(p)
{
front->next = t;
t->next = p;
}else
{
front->next = t;//插入最后
}
return head;
}
//创建链表
LinkNode* createList()
{
int data;
LinkNode *head,*p,*t;
head = new LinkNode;
head->next = 0;
p = head;
while(1)
{
cin >> data;
if(data ==0)
break;
t = new LinkNode;
t->data = data;
t->next = 0;
//t插入链表
head = insertlist(head,t);
}
return head;
}
//分离链表
LinkNode* split(LinkNode* head)
{
LinkNode* p,*front,*t;
LinkNode* head2 = new LinkNode;
head2->next = 0;
t = head2;
front = head;
p = front->next;
while(p)
{
if(p->data%2==0)
{
front->next = p->next;
t->next = p;
p->next = 0;
t = p;
p = front->next;
}else
{
front = p;
p = p->next;
}
}
return head2;
}
//显示链表
void showlist(LinkNode* head)
{
LinkNode* p = head->next;
while(p)
{
if(p == head->next)
cout << p->data;
else
cout <<"->"<<p->data;
p = p->next;
}
cout <<endl;
}
//分隔链表
int main()
{
LinkNode* head,*head1,*head2;
head = createList();
showlist(head);
head2 = split(head);
//显示
showlist(head);
showlist(head2);
return 0;
}