Leetcode Partition List 分割链表
2015-05-07 21:38
507 查看
题目:
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->2and x = 3,
return
1->2->2->4->3->5.
分析:
对于值大于等于x的节点,直接插到链表。对于值小于x的节点,需要找到第一个大于等于x的节点,插到它的前面。
Java代码实现:
/** * 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 dummy = new ListNode(0); ListNode node = dummy; node.next = null; while(head!=null) { if(head.val>=x) { while(node.next!=null) { node = node.next; } node.next = new ListNode(head.val); node.next.next = null; } else { while(node.next!=null && node.next.val < x) { node = node.next; } ListNode temp = node.next; node.next = new ListNode(head.val); node.next.next = temp; } node = dummy; head = head.next; } return dummy.next; } }
相关文章推荐
- leetcode_c++:链表:Partition List (086)
- leetcode:Partition List (链表处理)【面试算法题】
- leetcode---partition-list---链表
- 闲话链表(三) leetcode之Partition List
- leetcode Partition List二分链表问题
- LeetCode刷题笔记(链表):partition-list
- LeetCode OJ:Partition List(分割链表)
- leetcode 725. Split Linked List in Parts 链表均匀分割
- LeetCode(Partition List) 划分链表
- LeetCode Partition List(链表分段)
- LeetCode Partition List 按值分段链表 系统分析
- leetcode Partition List链表
- LeetCode2.2.3 @ Partition List 链表划分 D3F3
- leetcode:单链表之Partition List
- 86. Partition List&链表分割
- LeetCode 234 Palindrome Linked List (链表 快慢指针)
- LeetCode: Partition List [086]
- leetcode Rotate list (链表旋转)的python实现
- leetcode-Linked List Cycle II 链表判环以及求环起始位置
- LeetCode2.2.2 @ Reverse Linked List II 反转链表II D3F2