在本题中,插入并让其有序输出;使用单向循环链表来完成,声明几个函数来完成这个内容 struct ListNode{ int data,struct ListNode* next ;}
void insertList(ListNode* &head,int val)
{
ListNode *newList=new ListNode;// 给新指针创造空间
newList->val=val;
//如果头指针为空
if(head==NULL)
{
head=newList;
head->next=head;//形成环
return;
}
//如果插入值小于头节点值,则更新头节点的值;注意尾巴也应更新;
if(val<head->val)
{
newList->next=head;
ListNode* lastNode=head;
while(lastNode->next!=head)
{
lastNode=lastNode->next;
}
lastNode->next=newList;
head=newList;
}
//在链表中找到合适位置去插入
ListNode* curr=head;
while(curr->next!=head&&curr->next->val<val)
{
curr=curr->next;
}
newList->next=curr->next;
curr->next=newList;// 链接起来
}
同时应该声明一个打印函数
//打印链表
void print(ListNode* head)
{
if(head==NULL)
{
return;
}
ListNode* currNode=head;
do {
cout << currNode->val<< " ";
currNode=currNode->next;
} while (currNode!=head);
cout <<endl;
}
完整代码:
#include <iostream>
using namespace std;
struct ListNode
{
int val;
struct ListNode *next;
};
void insertList(ListNode* &head,int val)
{
ListNode *newList=new ListNode;
newList->val=val;
//如果头指针为空
if(head==NULL)
{
head=newList;
head->next=head;
return;
}
//如果插入值小于头节点值,则更新头节点的值;注意尾巴也应更新;
if(val<head->val)
{
newList->next=head;
ListNode* lastNode=head;
while(lastNode->next!=head)
{
lastNode=lastNode->next;
}
lastNode->next=newList;
head=newList;
}
//在链表中找到合适位置去插入
ListNode* curr=head;
while(curr->next!=head&&curr->next->val<val)
{
curr=curr->next;
}
newList->next=curr->next;
curr->next=newList;
}
//打印链表
void print(ListNode* head)
{
if(head==NULL)
{
return;
}
ListNode* currNode=head;
do {
cout << currNode->val<< " ";
currNode=currNode->next;
} while (currNode!=head);
cout <<endl;
}
int main()
{
ListNode* head=NULL;
while(true)
{
int selection;
cout << "Input a selection : ";
cin>>selection;
if(selection==1)
{
int val;
cout << "Input a number :";
cin>>val;
insertList(head, val);
}
else
break;
}
print(head);
return 0;
}