链表分割

题目来源:

牛客网--程序员面试金典

题目描述

编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前
给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。

解题思路

  1. 将小于x的值存放于node1链表中,将大于x的值存放于node2链表中
  2. 将node1和node2链表进行拼接

代码

import java.util.*;

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Partition {
    public ListNode partition(ListNode pHead, int x) {
        // write code here
        ListNode current = pHead;
        ListNode node1_head = null;
        ListNode node1_last = null;
        ListNode node2_head = null;
        ListNode node2_last = null;
        while(current != null){
            if(current.val < x){
                if(node1_head == null){
                    node1_head = new ListNode(current.val);
                    node1_last = node1_head;
                }else{
                    ListNode newNode =  new ListNode(current.val);
                    node1_last.next = newNode;
                    node1_last = newNode;
                    
                }
            }else{
               if(node2_head == null){
                    node2_head = new ListNode(current.val);
                    node2_last = node2_head;
                }else{
                    ListNode newNode =  new ListNode(current.val);
                    node2_last.next = newNode;
                    node2_last = newNode;
                    
                }
            }
            current = current.next;
        }
        if(node1_head == null){
            return node2_head;
        }else{
            node1_last.next = node2_head;
            return node1_head;
        }
        
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 题目:以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前给定一个链表的头指针 List...
    FlyElephant阅读 398评论 0 0
  • B树的定义 一棵m阶的B树满足下列条件: 树中每个结点至多有m个孩子。 除根结点和叶子结点外,其它每个结点至少有m...
    文档随手记阅读 13,294评论 0 25
  • 第一章 绪论 什么是数据结构? 数据结构的定义:数据结构是相互之间存在一种或多种特定关系的数据元素的集合。 第二章...
    SeanCheney阅读 5,807评论 0 19
  • Java8张图 11、字符串不变性 12、equals()方法、hashCode()方法的区别 13、...
    Miley_MOJIE阅读 3,726评论 0 11
  • 很多人说,职场对女性太不公平,尤其是职场妈妈尤其艰难。其实,你工作做不好这个锅,孩子真的不能背。 01 女儿出生前...
    林叨叨阅读 664评论 0 3