美文网首页
链表分割

链表分割

作者: 努力努力再努力_姜姜 | 来源:发表于2016-06-23 17:01 被阅读127次

题目来源:

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

题目描述

编写代码,以给定值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的结点排在...

  • Split Linked List in Parts

    解决思路 直接求出链表长度,除以k得到每个链表长度d,同样求出余数a,即前a个元素长度为d+1,遍历链表分割即可。

  • LeetCode 第148题:排序链表

    1、前言 2、思路 使用归并排序的思想,首先找到链表中点,然后分割成左右两个链表,一直分割到不能分为止;然后在两两...

  • 86.分割链表

    题目给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。 你应当...

  • 按值分割链表

    按值分割链表 [https://imgchr.com/i/spyJ3Q] [https://leetcode-cn...

  • leetcode -86 分割链表

    题目:https://leetcode-cn.com/problems/partition-list/[https...

  • 面试题 02.04. 分割链表

    面试题 02.04. 分割链表[https://leetcode-cn.com/problems/partitio...

  • Leetcode-面试题 02.04 分割链表

    面试题 02.04. 分割链表[https://leetcode-cn.com/problems/partitio...

  • 026-partition list

    描述 在一个单链表中,给定一个值X,根据X将链表分割成两部分,小于X的节点在大于等于X节点的左面。 在分割成的两部...

  • 86. Partition List 分割链表

    题目 给定一个链表头 head 和值 x,将这个链表分割,使得所有小于 x 的节点,都位于x节点的左侧。 解析 让...

网友评论

      本文标题:链表分割

      本文链接:https://www.haomeiwen.com/subject/loxodttx.html