前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode86. 分隔链表

LeetCode86. 分隔链表

作者头像
mathor
发布2018-08-17 15:50:30
4090
发布2018-08-17 15:50:30
举报
文章被收录于专栏:mathormathor
题目链接:LeetCode86

 这道题类似荷兰国旗,说一下做法,最简单的方法就是直接将所有的值保存到数组中,然后对数组进行划分,完了以后再重新插回链表中。但是这道题有一个附加要求,要保留每个节点的相对位置,所以这道题应该这么做,首先创建4个节点,分别是ps,pe,qs,qe,然后遍历一遍链表,每次遍历到的当前值cur如果小于指定的值,就将其插到p节点中去,否则就插到q节点中去

代码语言:javascript
复制
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
class Solution {
    public ListNode partition(ListNode Head, int x) {
        ListNode ps = null;//p start
        ListNode pe = null;//p end
        ListNode qs = null;//q start
        ListNode qe = null;//q end
        ListNode current = Head;
        while(current != null) {
            ListNode temp = current.next;
            current.next = null;
            if(current.val < x) {
                if(ps == null) {
                    ps = current;
                    pe = current;
                }
                else {
                    pe.next = current;
                    pe = current;
                }
            }
            else{
                 if(qs == null) {
                    qs = current;
                    qe = current;
                }
                else {
                    qe.next = current;
                    qe = current;
                }
            }
            current = temp;
        }
        if(ps == null)
            return qs;
        pe.next = qs;
        return ps;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-08-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目链接:LeetCode86
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档