leetcode -- 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 tox.

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的节点

在头指针位置先插入一个干扰元素,以保证head永不为空,然后在最后返回的时候删除掉

链表操作,需总结

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode partition(ListNode head, int x) {
14         // Start typing your Java solution below
15         // DO NOT write main() function
16            ListNode p = new ListNode(Integer.MIN_VALUE);
17            p.next = head;
18            head = p;
19            
20            ListNode pre = null;
21            while(p != null && p.val < x){
22                pre = p;
23                p = p.next;
24            }
25            
26            if(p != null){
27                ListNode cur = pre;
28                while(p != null){
29                    if(p.val < x){
30                         pre.next = p.next;
31                         ListNode tmp = cur.next;
32                         cur.next = p;
33                         p.next = tmp;
34                         cur = cur.next;
35                         p = pre;
36                    }
37                    pre = p;
38                    p = p.next;
39                }
40            }
41            return head.next;
42     }
43 }

 

转载于:https://www.cnblogs.com/feiling/p/3251953.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值