LeetCode - 86、分隔链表

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

示例:

    输入: head = 1->4->3->2->5->2, x = 3
    输出: 1->2->2->4->3->5

1 /**
2  * 列表定义
3  * public class ListNode {
4  *     int val;
5  *     ListNode next;
6  *     ListNode(int x) { val = x; }
7  * }
8  */

解法:

 1 class Solution {
 2     public ListNode partition(ListNode head, int x) {
 3         if(head == null || head.next == null) {
 4             return head;
 5         }
 6         
 7         ListNode bigDump = new ListNode(0);
 8         ListNode smallDump = new ListNode(0);
 9         ListNode big = bigDump;
10         ListNode small = smallDump;
11         while(head != null) {
12             if (head.val >= x) {
13                 big.next = head;
14                 big = big.next;
15             } else {
16                 small.next = head;
17                 small = small.next;
18             }
19             head = head.next;
20         }
21         big.next = null;
22         small.next = bigDump.next;
23         return smallDump.next;    
24     }
25 }
View Code

说明:使用双指针的方式,分别记录小于、大于等于的列表部分。然后在将其拼接起来。

注意:需要创建两个临时变量来存储两个新列表的头部地址

猜你喜欢

转载自www.cnblogs.com/dkccc/p/11429883.html