链表:链表分割

Posted wanggm

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了链表:链表分割相关的知识,希望对你有一定的参考价值。

题目描述

编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前

给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。

 

import java.util.*;

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Partition {
    public ListNode partition(ListNode pHead, int x) {
        // write code here
        if (pHead == null || pHead.next == null) {
            return pHead;
        }
        ListNode headNode = new ListNode(9999); // 自定义头结点。添加头结点能方便运算。
        headNode.next = pHead;
        ListNode pre = headNode;
        ListNode p = pHead;
        ListNode q = pHead.next;
        p.next = null;
        while (q != null) { // 尾插法
            if (q.val < x) {
                while (p != null && p.val < x) {
                    pre = p;
                    p = p.next;
                }
                ListNode s = q;
                q = q.next;
                pre.next = s;
                s.next = p;
            } else {
                while (p != null) {
                    pre = p;
                    p = p.next;
                }
                ListNode s = q;
                q = q.next;
                pre.next = s;
                s.next = p;
            }
            pre = headNode;
            p = pre.next;
        }
        return p;
    }
}

 

 

以上是关于链表:链表分割的主要内容,如果未能解决你的问题,请参考以下文章

链表分割

链表面试-链表分割(常考题)

链表oj---->链表分割

链表分割

CM11 链表分割

CM11 链表分割