Write code to partition a linked list around a value x, such that all nodes less than x
come before alt nodes greater than or equal to.

分割一个链表,将值小于x的节点全部放在其他节点的前面。

解答:

我们可以创建两个不同的链表,其中一个用来连接比x小的节点,另外一个则连接大于等于x的节点,然后合并两个链表即可。

public class Main {
public static void appendToTail(List head, int d) {
List end = new List(d);
List n = head;
while (n.next != null) {
n = n.next;
}
n.next = end;
} public static void print(List head) {
List n = head;
System.out.print("{");
while (n != null) {
if (n.next != null)
System.out.print(n.data + ", ");
else
System.out.println(n.data + "}");
n = n.next;
}
} public static List partition(List head, int x) {
List small = null;
List large = null;
List largeHead = null;
List smallHead = null;
while (head != null) {
List next = head.next;
head.next = null;
if (head.data < x) {
if (small == null) {
small = head;
smallHead = small;
} else {
small.next = head;
small = small.next;
}
} else {
if (large == null) {
large = head;
largeHead = large;
} else {
large.next = head;
large = large.next;
}
}
head = next;
}
if(small == null)
{
return largeHead;
}
small.next = largeHead;
return smallHead;
} public static void main(String args[]) {
List list = new List(0);
appendToTail(list, 9);
appendToTail(list, 8);
appendToTail(list, 7);
appendToTail(list, 6);
appendToTail(list, 5);
appendToTail(list, 4);
appendToTail(list, 3);
appendToTail(list, 2);
appendToTail(list, 1);
print(list);
print(partition(list, 5));
}
} class List {
int data;
List next; public List(int d) {
this.data = d;
this.next = null;
} public List() {
}
}

最新文章

  1. 使用nodejs搭建图片服务器(一)
  2. appSetting 在单独文件的读写
  3. javaScript特效
  4. 动态加载Ribbon功能区
  5. 散文说python半篇——景观三元论与盖茨比的对话
  6. C++中类的大小计算方法总结《网络+总结》
  7. xgboost-python参数深入理解
  8. where id in用 order by field 保持排序
  9. [HNOI2008]水平可见直线
  10. Oracle 11g ogg单表初始化步骤
  11. ConcurrentDictionary对象
  12. Java Hibernate中的悲观锁和乐观锁的实现
  13. 进程命令ps/top/kill
  14. Git科普来一发:【rebase】与【merge】
  15. 媒体查询漫谈——@media Queries
  16. 将本地的mongodb迁移到阿里云
  17. JQuery 之 重置表单的方法
  18. python开发_HTMLParser_html文档解析
  19. Linux的发行版之间的联系和区别
  20. (asp.net)百度浏览器Cookie的神奇bug

热门文章

  1. 统计学习导论:基于R应用——第二章习题
  2. BaseAdapter以及对ListView的优化(转)
  3. python与数值计算环境搭建
  4. (转)PHP模板smarty简单入门教程
  5. target,currentTarget,delegateTarget,srcElement
  6. windows 8.1 administrator相关设置
  7. iOS9升级后第三方平台无法分享的问题
  8. Xcode 的正确打开方式——Debugging(转)
  9. MySQL被Oracle并购后的409个日日夜夜
  10. /root/.bashrc与/etc/profile的异同