标签:
编写代码,以给定值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
Queue<ListNode>q1=new LinkedList<>();
Queue<ListNode>q2=new LinkedList<>();
while(pHead!=null){
if(pHead.val<x)
q1.offer(pHead);
else{
q2.offer(pHead);
}
pHead=pHead.next;
}
ListNode tmp=null;
if(!q1.isEmpty()){
pHead=q1.poll();
}else if(!q2.isEmpty()){
pHead=q2.poll();
}
tmp=pHead;
while(!q1.isEmpty()){
tmp.next=q1.poll();
tmp=tmp.next;
}
while(!q2.isEmpty()){
tmp.next=q2.poll();
tmp=tmp.next;
}
tmp.next=null;
return pHead;
}
}
标签:
原文地址:http://www.cnblogs.com/mlz-2019/p/4757849.html