zoukankan      html  css  js  c++  java
  • 2.4---把链表划分为两部分(CC150)

    注意,题目要求要保持两部分的相对顺序,所以,用交换是不行的。

    import java.util.HashSet;
    import java.util.Set;
    
    class ListNode{
        int val;
        ListNode next;
        ListNode(int x){
            val = x;
        }
    }
    
    public class Solution{
    
        public static void main(String[] args){
            ListNode head = new ListNode(3);
            head.val = 3;
            ListNode node = new ListNode(1);
            node.val = 1;
            head.next = node;
            ListNode tmp = head;
            while(tmp != null){
                System.out.println(tmp.val);
                tmp = tmp.next;
            }
            tmp = partition(head,2);
            System.out.println("delete");
    
            while(tmp != null){
    
                System.out.println(tmp.val);
                tmp = tmp.next;
            }
        }
        public static ListNode partition(ListNode head, int x) {
            //思路:用两个链表记录一下两部分,然后合并
            if(null == head)
                return head;
            ListNode greater = new ListNode(0);//小的
            ListNode smaller = new ListNode(0);//>=
            ListNode tmp1 = greater;
            ListNode tmp2 = smaller;
    
            ListNode tmp = head;
            while(tmp != null)
            {
                if(tmp.val < x)
                {
                    ListNode n = new ListNode(tmp.val);
                    tmp2.next = n;
                    tmp2 = tmp2.next;//error: not write
                }
                else
                {
                    ListNode m = new ListNode(tmp.val);
                    tmp1.next = m;
                    tmp1 = tmp1.next;//error: not write
                }
                tmp = tmp.next;//总是忘记写这一步
            }
            //最后合并
            tmp1.next = null;
            tmp2.next = greater.next;
            return smaller.next;
        }
    }

      

  • 相关阅读:
    回溯法---哈密顿回路(5)
    回溯法---n皇后问题(4)
    回溯法---n-着色问题(3)
    回溯法--算法框架(2)
    创建二叉树的所有深度上的节点链表
    笔试
    笔试 (2)
    LeetCode278-第一个错误的版本(二分查找)
    LeetCode46-全排列(递归)
    LeetCode258-各位相加(猜想公式)
  • 原文地址:https://www.cnblogs.com/yueyebigdata/p/5053463.html
Copyright © 2011-2022 走看看