标签:util describe 代码 return des tle code class desc
编写代码,以给定值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; } }
标签:util describe 代码 return des tle code class desc
原文地址:https://www.cnblogs.com/wanggm/p/9678185.html