Leetcode 147链表插入排序多种方法实现之C语言

cocowy的编程之旅

示例:
这里是引用

  1. 对于一个链表排序,我们可以有多种方法,
    (1)递归
public class ListNode {

int val;
ListNode next;
ListNode(int x) { val = x; }
}
class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode res = null;
ListNode p = head;
while(p != null) {
ListNode next = p.next;
res = insert(res, p);
p = next;
}

 return res;
}

private ListNode insert(ListNode head, ListNode node) {
if(head == null || head.val > node.val) {
node.next = head;
return node;
}

 head.next = insert(head.next, node);
 return head;
}
}

(2)此为第二种,链表不进行增断链表,而是进行指针值的变动

struct ListNode* insertionSortList(struct ListNode* head) {
if(!head)
return NULL;
struct ListNode * p,*q;
int temp;

for(p=head;p;p=p->next)
{
for(q=p->next;q;q=q->next)
{
if(p->val>q->val)
{
temp=p->val;
p->val=q->val;
q->val=temp;
}
}

}
return head;
}

(3)此为第三种,在前面加一个头结点进行断链增链操作(新的链表排序)

struct ListNode* insertionSortList(struct ListNode* head) {
if(!head)
return NULL;

struct ListNode *L,*p,q;
L=(struct ListNode)malloc(sizeof(struct ListNode));
L->next=head;

p=head->next;
head->next=NULL;
while(p)
{
struct ListNode *curr=p->next;
q=L;
while(q->next&&q->next->val<=p->val)
q=q->next;
p->next=q->next;
q->next=p;
p=curr;
}
return L->next;
}

(4)指针值不动,不增加新的链表。(用原链表进行排序)

struct ListNode* insertionSortList(struct ListNode* head){
    if(head==NULL||head->next==NULL) return head;
    struct ListNode* rear,*p,*temp,*q ;      //rear指向尾结点,q指向倒数第二个结点

    rear = head->next;
    q=head;
    while(rear)
    {
        //找到不是升序的结点进行插入
        while(rear&&rear->val>=q->val)
        {
            q = q->next;
            rear = rear->next;
        }
        if(rear==NULL)   break;
        temp = rear;
        rear = rear->next;//更新结点
    
        //该节点小于头结点(特殊结点,头插法)
        if(temp->val<head->val)
        {
            temp->next = head;
            head = temp;
        }
        else//在链表中搜寻合适的插入位置
        {
            p = head;
            while(temp->val>p->next->val)
                p = p->next;
            temp->next = p->next;
            p->next = temp;
        }
        q->next=rear;//始终为相邻结点比较
    }
    return head;
}

作者:cocowy
链接:https://leetcode-cn.com/problems/insertion-sort-list/solution/pai-xu-de-san-chong-si-lu-di-gui-zeng-duan-lian-bi/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

作者:cocowy
链接:https://leetcode-cn.com/problems/insertion-sort-list/solution/pai-xu-de-san-chong-si-lu-di-gui-zeng-duan-lian-bi/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值