您的位置:首页 > 财经 > 产业 > LeetCode 面试题02.04.分割链表

LeetCode 面试题02.04.分割链表

2024/10/5 18:30:55 来源:https://blog.csdn.net/m0_63816268/article/details/140404621  浏览:    关键词:LeetCode 面试题02.04.分割链表

LeetCode 面试题02.04.分割链表 C写法

image-20240713175326367

思路🤔:

​ 将x分为两段,一段放小于x的值,另一段放大于x的值。开辟四个指针lesshead、lesstail、greaterhead、greatertail,head为哨兵位,防止链表为空时情况过于复杂,tail为尾结点,将链表的值进行大小判断后尾插完成分段,分段后再链接,最后释放哨兵位完成整个链表的分割。

代码:

struct ListNode* partition(struct ListNode* head, int x){struct ListNode* lesshead,*lesstail,*greaterhead,*greatertail;lesshead = lesstail = (struct ListNode*)malloc(sizeof(struct ListNode));greaterhead = greatertail = (struct ListNode*)malloc(sizeof(struct ListNode));lesstail->next = greatertail->next = NULL; //将链表分为两段存储struct ListNode* cur = head;while(cur){if(cur->val < x) //小于x尾插在less段{lesstail->next = cur;lesstail = lesstail->next;}else{greatertail->next = cur;greatertail = greatertail->next;}cur = cur->next;}lesstail->next = greaterhead->next; //链接两段链表,哨兵位不放数据所以要链接到nextgreatertail->next = NULL; //单链表最后要指向空struct ListNode* list = lesshead->next; //完整链表free(greaterhead);free(lesshead);return list;
}

image-20240713185458069

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com