leetcode-86 分隔链表
生活随笔
收集整理的這篇文章主要介紹了
leetcode-86 分隔链表
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給定一個(gè)鏈表和一個(gè)特定值 x,對(duì)鏈表進(jìn)行分隔,使得所有小于 x 的節(jié)點(diǎn)都在大于或等于 x 的節(jié)點(diǎn)之前。
你應(yīng)當(dāng)保留兩個(gè)分區(qū)中每個(gè)節(jié)點(diǎn)的初始相對(duì)位置。
示例:
輸入: head = 1->4->3->2->5->2, x = 3
輸出: 1->2->2->4->3->5
使用雙指針的方式,各自構(gòu)造一個(gè)大元素的頭節(jié)點(diǎn)和小元素的頭節(jié)點(diǎn),同時(shí)遍歷當(dāng)前鏈表完善大小鏈表,最終將兩個(gè)大小鏈表鏈接起來即可
ListNode* partition(ListNode* head, int x) {if (head == NULL) return NULL;ListNode small(0);ListNode big(0);ListNode *pre_small = &small;ListNode *pre_big = &big;while(head) {if (head -> val < x) {pre_small -> next = head;pre_small = head;} else {pre_big -> next = head;pre_big = head;}head = head -> next;}pre_small -> next = big.next;pre_big -> next = NULL;return small.next;
}
總結(jié)
以上是生活随笔為你收集整理的leetcode-86 分隔链表的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode-142 环形链表II
- 下一篇: leetcode-21 合并两个有序链表