86. Partition List

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

这道题没看答案之前不明白到底如何移动,看了答案发现太简单了。new两个链表,遍历原链表,把val大于等于x的节点接到big后面,把val小于x的节点接到small后面,最后把big接到small后面,就可以了。

WechatIMG53.jpeg
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode partition(ListNode head, int x) {
        if (head == null || head.next == null){
            return head;
        }
        ListNode big = new ListNode(-1);
        ListNode small = new ListNode(-1);
        ListNode bighead = big;
        ListNode smallhead = small;
        while (head != null){
            if (head.val < x){
                smallhead.next = head;
                smallhead = smallhead.next;
            } else {
                bighead.next = head;
                bighead = bighead.next;
            }
            head = head.next;
        }
        bighead.next = null;
        smallhead.next = big.next;
        return small.next;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容