Leetcode -- 86. Partition List (以及关于没有头结点链表遍历修改的问题)
2017-03-18 11:20
453 查看
86. Partition List
英文原题
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.
中文翻译
给定一个链表和值x,对它进行划分,使得小于x的所有节点都在大于或等于x的节点之前。应该保留两个分区中每个分区中节点的原始相对顺序。
具体的思路
建立两个链表,一个放比X值大的节点,一个放比X值小的节点。最后把两个链表拼接在一起。代码实现如下
public static ListNode partition(ListNode head, int x) { if(head == null || head.next == null) return head; ListNode p = head; ListNode fir = new ListNode(0); ListNode sec = new ListNode(1); ListNode rf = fir; ListNode rc = sec; int i = 0 ; while(p != null) { ListNode temp = p.next; if(p.val < x) { //后插法抽取节点形成新的链表 rf.next = p; p.next = null; rf = p; } else { rc.next = p; p.next = null; rc = p; } p = temp; } rf.next = sec.next; return fir.next; }
思考
在做这个题的过程中,有一个产生了一个问题:一个链表如果没有头结点,怎么遍历删除?:
在链表中删除一个节点, 一般情况下要知道当前要删除节点p的前一个节点 pre 。如果没有头结点的话,我们很难遍历删除这样的节点。
所以,想到一个新的方法来删除当前节点p
我们把p节点的下一个节点的属性赋值给p,然后让p指针指向下一个节点的下一个节点,通过这种方式我们就“变相”的删除了p节点
p = p.next.value; p = p.next.next;
以后希望能有一个机会,把遇到的问题总结一下,出一个汇总贴吧。
2017-3-18 design by zx
相关文章推荐
- 用C语言编写一个双链表,每个结点存储学生的编号以及姓名,遍历这个双链表,并将学号按照从小到大进行排序
- 关于js遍历list集合,获取select选中的值以及动态添加option
- 判断两链表相交的问题(分有环和无环,以及求第一个相交结点)
- [MySQL] 实现树形的遍历(关于多级菜单栏以及多级上下部门的查询问题)
- 【LeetCode-面试算法经典-Java实现】【083-Remove Duplicates from Sorted List(排序的单链表中删除重复的结点)】
- 关于修改frameworks的源码遇到的一点问题以及解决方法
- [MySQL] 实现树形的遍历(关于多级菜单栏以及多级上下部门的查询问题)
- [leetcode] Delete Node in a Linked List 删除链表中的一个结点
- 关于导入的工程没有权限修改的问题
- MySQL 实现树形的遍历(关于多级菜单栏以及多级上下部门的查询问题)
- 学习ORACLE中关于配置文件的读取和修改心得以及问题
- LeetCode | Remove Duplicates from Sorted List II(删除链表中重复结点2)
- leetcode:Reorder List (修改链表排列不改变值) 【面试算法题】
- 尽管关于Java中文问题的讨论已经相当多了,但由于Java的相关技术标准繁多,面向Java的Web服务器、应用服务器以及JDBC数据库驱动等都没有官方的标准,所以Java应用在处理中文时所存在的问
- 关于修改frameworks的源码遇到的一点问题以及解决方法
- 关于动态存储分配函数的调用,在已经过排序的数组中查找及删除内容的操作,余数的分析,删除字符数组中的空格,对链表的逆置,在源字符串中查找子字符串的个数,函数指针以及函数的调用,循环赋值带来的问题以及插入
- 【LeetCode】Remove Nth Node From End of List && 【九度】题目1517:链表中倒数第k个结点
- LeetCode | Remove Nth Node From End of List(移除链表中倒数第n个结点)
- 关于Redis修改配置没有效果的问题分析
- 关于tomcat端口的修改,以及同时部署多个应用,自己遇到的问题以及解决办法