单循环链表(理解)

9befe00510354c8abd36fc4c8e8989eb.png

 在本题中,插入并让其有序输出;使用单向循环链表来完成,声明几个函数来完成这个内容  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;
}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JXF111400

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值