链表划分

问题来源:选自LeetCode 86:分隔链表

问题描述: 

题目给定信息:给定一个链表,我们要把链表按照给定值进行分割,使分割后的链表所有小于给定值的节点都在给定值的左边,且相对位置不变,所有大于给定值的节点都在给定值的右边,且相对位置不变。

问题分析:

  我们可以定义两个临时头节点,这两个临时节点分别存放所有小于给定值的节点和所有大于等于给定值的节点,然后再把这两个临时链表拼接起来。遍历原链表,每遍历到一个节点都和给定值进行判断,然后根据判断结果确定该节点应该放在哪一个临时链表的中。

函数实现:

 1  public ListNode partition(ListNode head, int x) {
 2         ListNode less_head=new ListNode(0);
 3         ListNode more_head=new ListNode(0);
 4         ListNode less_pre=less_head;
 5         ListNode more_pre=more_head;
 6         while(head!=null){
 7             ListNode next=head.next;
 8             if(head.val<x){
 9                 less_pre.next=head;
10                 less_pre=less_pre.next;
11                 head.next=null;
12             }else{
13                 more_pre.next=head;
14                 more_pre=more_pre.next;
15                 head.next=null;
16             }
17             head=next;
18         }
19         //将两部分拼接起来
20         less_pre.next=more_head.next;
21         more_head.next=null;
22         return less_head.next;
23     }

运行结果:

原文地址:https://www.cnblogs.com/BaoZiY/p/10685164.html