LeetCode.86 Partition List
来源:互联网 发布:软件研发队伍介绍 编辑:程序博客网 时间:2024/06/06 11:03
题目:
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2
and x = 3,
return 1->2->2->4->3->5
.
class Solution { public ListNode partition(ListNode head, int x) { //根据给定值划分链区,小的在左边,大的在其后面(小的放前面,大的放后面)//小的插入头结点后面,大于等于不移动 ListNode dummy = new ListNode(0);dummy.next = head;ListNode res = dummy;ListNode pre = dummy;ListNode cur = head;while (cur != null) {if (cur.val < x) {// 小于pre.next = cur.next;ListNode temp = pre.next;cur.next = dummy.next;dummy.next = cur;dummy = dummy.next;if(pre.next==cur){//判断当前节点是否为原位置pre=pre.next;}cur = temp;} else {// 大于等于pre = pre.next;cur = cur.next;}}return res.next; }}
参考答案:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */class Solution { public ListNode partition(ListNode head, int x) { //利用两个链表,一个用来装小于的,另一个用来装大于或者等于。 //最后通过拼接两个链表,返回结果 ListNode dummy1 = new ListNode(0);//小的 ListNode dummy2 = new ListNode(0); //大于等于 ListNode curr1 = dummy1, curr2 = dummy2; //标志位 while (head!=null){ if (head.val<x) { curr1.next = head; curr1 = head; }else { curr2.next = head; curr2 = head; } head = head.next; } //拼接,curr2.next置空防止循环 curr2.next = null; curr1.next = dummy2.next; return dummy1.next; }}
阅读全文
0 0
- LeetCode 86: Partition List
- LeetCode 86 Partition List
- [leetcode 86] Partition List
- leetcode-86 Partition List
- [LeetCode 86]Partition List
- leetcode || 86、Partition List
- LeetCode---(86) Partition List
- LeetCode 86 Partition List
- Leetcode[86]-Partition List
- leetcode[86]:Partition List
- Leetcode #86 Partition List
- LeetCode(86) Partition List
- leetcode 86: Partition List
- [Leetcode]#86 Partition List
- leetCode #86 Partition List
- leetcode 86:Partition List
- 【leetcode】【86】Partition List
- leetcode-Partition List-86
- java类加载机制
- 高德地图加载海量点
- 关于SpringMVC中action模型参数的小知识
- NYOJ685 查找字符串(字典树)
- android获取全局context
- LeetCode.86 Partition List
- 【PAT】【Advanced Level】1117. Eddington Number(25)
- Android下生成和读取PDF文件的工程demo, ttf的使用
- 词法分析器
- hibernate无限递归问题
- 新手小白入驻自媒体应该如何运营
- Arcgis---绘制多边形
- RabbitMQ 介绍
- Python04_函数式编程