zoukankan      html  css  js  c++  java
  • 链表分割

    题目描述

    编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前

    给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。

     1 import java.util.*;
     2 
     3 /*
     4 public class ListNode {
     5     int val;
     6     ListNode next = null;
     7 
     8     ListNode(int val) {
     9         this.val = val;
    10     }
    11 }*/
    12 public class Partition {
    13     public ListNode partition(ListNode pHead, int x) {
    14         // write code here
    15         ListNode beforeBg = null, beforeEd = null,
    16                 afterBg = null,afterEd = null;
    17         while(pHead != null)
    18         {
    19             ListNode next = pHead.next;
    20             pHead.next = null;
    21             if(pHead.val <x)
    22             {
    23                 if(beforeBg == null)
    24                 {
    25                     beforeBg = pHead;
    26                     beforeEd = pHead;
    27                 }
    28                 else
    29                 {
    30                     beforeEd.next = pHead;
    31                     beforeEd = pHead;
    32                 }
    33             }
    34             else
    35             {
    36                 if(afterBg == null)
    37                 {
    38                     afterBg = pHead;
    39                     afterEd = pHead;
    40                 }
    41                 else
    42                 {
    43                     afterEd.next = pHead;
    44                     afterEd = pHead;
    45                 }
    46             }
    47             pHead = next;
    48         }
    49         
    50         if(beforeBg == null) return afterBg;
    51         beforeEd.next = afterBg;
    52         return beforeBg;
    53     }
    54 }
  • 相关阅读:
    直线型一阶倒立摆5---硬件平台搭建
    PE view---重要参数--C语言实现
    A1132. Cut Integer
    A1131. Subway Map (30)
    A1130. Infix Expression
    A1129. Recommendation System
    A1128. N Queens Puzzle
    A1127. ZigZagging on a Tree
    A1126. Eulerian Path
    A1125. Chain the Ropes
  • 原文地址:https://www.cnblogs.com/xiaoyesoso/p/5342485.html
Copyright © 2011-2022 走看看