LeetCode#86. Partition List

来源:互联网 发布:鸿图网络危机公关公司 编辑:程序博客网 时间:2024/06/05 18:55
  • 题目:链表分块(比target小的在左边,比target大的在右边,并且元素之间保持原来的顺序)
  • 难度:Medium
  • 思路:定义两个头结点,分别将比target小、不小于target的节点连接,遍历完原始链表后需要释放left后面的元素
  • 代码:
/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode partition(ListNode head, int x) {        if(head == null || head.next == null){            return head;        }        ListNode leftHead = new ListNode(0);        ListNode rightHead = new ListNode(0);        ListNode left = leftHead;        ListNode right = rightHead;        ListNode node = head;        while(node != null){            if(node.val < x){                left.next = node;                left = left.next;            }else{                right.next = node;                right = right.next;            }            node = node.next;;        }        left.next = rightHead.next;        right.next = null;        return leftHead.next;    }}
0 0
原创粉丝点击