leetcode上的Sort a linked list using insertion sort

本地编写的时候使用的是具有头指针的链表,头指针为空,代码如下

#include"iostream"
using namespace std;
//
typedef struct List
{
struct List* next;
int value;
}List;
List *head = NULL;
List *initList()
{
head = new List;
head->next = NULL;
return head;
}
List *createList(int value)
{
List *p = new List;
p->value = value;
p->next = head->next;
head->next = p;
return head;
}
void printList()
{
List* p = head->next;
while (p != NULL)
{
cout << p->value << " ";
p = p->next;
}
}
List *insertSort()
{
List *vhead = head->next;//vhead为第一个有值的指针
if (vhead == NULL||vhead->next==NULL)
return head;
List *p = vhead->next;
List *vheadB = head;//记录插入位置前面的指针
while (vhead!=NULL||p!=NULL)
{
if (p->value < vhead->value)
{
List *q = head;
while (q->next != p)
q = q->next;
//删除位置的操作
q->next = p->next;
//插入位置的操作
p->next = vhead;
vheadB->next = p;
vhead = p;
//还原p的位置
p = q->next;
}
else
p = p->next;
if (p == NULL)
{
vheadB = vhead;
vhead = vhead->next;
p = vhead->next;
}
if (vhead->next == NULL)
return head;
}
}
int main()
{
initList();
int a;
cin >> a;
while (a != -1)
{
createList(a);
cin >> a;
}
printList();
cout << endl;
insertSort();
printList();
return 0;
}

提交到网站时,使用的是没有头指针的链表,结构体使用默认创建的。有无头指针两种方式,原理一致,无头指针代码如下

#include"iostream"
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if (head == NULL || head->next == NULL)
return head;
ListNode *headNew = head;
ListNode *headB = head;
int count = 0;
ListNode *p = head->next;
while (true)
{
if (head->val>p->val)
{
ListNode *q = headNew;
while (q->next != p)
q = q->next;
//delete
q->next = p->next;
//insert,如果head还指向第一元素,则直接在最前面插入即可
p->next = head;
if (count != 0)
headB->next = p;
head = p;
//resolve p
p = q->next;
}
else
p = p->next;
if (p == NULL)
{

//headNew记录链表的第一个指针,head发生变化
if (count == 0)
headNew = head;
count++;
headB = head;
head = head->next;
p = head->next;
}
if (head->next == NULL)
return headNew;
}
return headNew;
}
};

//输入链表元素
void printList(ListNode *head)
{
if (head == NULL)
return;
while (head != NULL)
{
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
int main()
{
int a;
int count = 0;
ListNode *head = NULL;

//输入元素创建链表
cin >> a;
while (a != -1)

if (count == 0)
head = new ListNode(a);
else
{
ListNode *q = new ListNode(a);
q->next = head;
head = q;
}
count++;
cin >> a;
}
printList(head);
Solution *s = new Solution();
ListNode *headNew=s->insertionSortList(head);
printList(headNew);
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值