LeetCode86 Partition List

LeetCode86 Partition List

問題來源LeetCode86

問題描述

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.

問題分析

這道題就是鏈表的簡單操作,思路就是初始化兩個node,把大於x的放置到一個node下,小於等於x的放置到另外一個node下,最後把兩個node連接起來。

需要注意的是在掛接到node下的時候,需要把當前node的next置爲null,不會然導致超出空間大小。

代碼如下

/**
    * Definition for singly-linked list.
    * public class ListNode {
    * int val;
    * ListNode next;
    * ListNode(int x) { val = x; }
    * }
    */
public ListNode partition(ListNode head, int x) {
    if(head==null)
        return head;
    ListNode myhead = new ListNode(0);
    ListNode left= new ListNode(0);
    myhead.next = left;
    ListNode right = new ListNode(0);
    ListNode midHead = new ListNode(0);
    midHead.next = right;
    while(head!=null){
        ListNode node = head.next;
        if(head.val<x){
            left.next = head;
            left = left.next;
            left.next = null;
        }else {
            right.next = head;
            right = right.next;
            right.next = null;
        }
        head= node;
    }
    left.next = midHead.next.next;
    return myhead.next.next;
}

LeetCode學習筆記持續更新

GitHub地址 https://github.com/yanqinghe/leetcode

CSDN博客地址 http://blog.csdn.net/yanqinghe123/article/category/7176678

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章