链表插入排序:LinkList:Sort a LinkList(insert directly)

本文介绍了一种基于链表的数据结构实现的排序算法。通过创建链表并利用节点指针进行遍历,该算法能够在每次迭代中将一个新元素插入到已排序的链表中,确保最终得到完全排序的链表。此方法对于理解链表操作及排序原理非常有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// ListSort.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
using namespace std;
typedef struct _node
{
 int data;
   struct _node *next;
}Node;


int _tmain(int argc, _TCHAR* argv[])
{
 int arr[]={12,34,1,89,6,56,45,2,31};
 Node* head=new Node();
 Node* p=head;
 for(int i=0;i<9;i++)
 {
  Node* n=(Node*)malloc(sizeof(Node));
  n->data=arr[i];
  n->next=NULL;
  p->next=n;
  p=p->next;
 }
head=head->next;

Node* temp=head->next;
head->next=NULL;

while(temp)
{
   Node* p=temp->next;
  for(Node *t=head;t!=NULL;t=t->next)
  {
   if(temp->data>t->data&&t->next!=NULL&&(t->next)->data>temp->data)
   {
    temp->next=t->next;
       t->next=temp;
    break;
   }
   else if(temp->data>t->data&&t->next==NULL)
   {
    t->next=temp;
    temp->next=NULL;
    break;
   }
   else if(temp->data<t->data)
   {
    temp->next=head;
    head=temp;
    break;
   }  
  }
  temp=p;
 
}
 while(head)
 {
  cout<<head->data<<" ";
  head=head->next;
 }
 cin.get();
 return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值