zoukankan      html  css  js  c++  java
  • Partition List,拆分链表

    问题描述:

    Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

    You should preserve the original relative order of the nodes in each of the two partitions.

    For example,
    Given 1->4->3->2->5->2 and x = 3,
    return 1->2->2->4->3->5.

    算法分析:开始我只是想在原来链表上进行操作,但是无法返回头结点。这道题区别链表反转,链表反转不用新建链表,只用在原有的链表上操作就行了。这道题,要新建两个新的链表,一个链表的元素全部小于目标值,另一个链表的元素全部大于目标值。然后把这两个链表连接起来。

    public ListNode partition(ListNode head, int x)
    	{
    		if(head == null || head.next == null)
    		{
    			return head;
    		}
    		ListNode lessHead = new ListNode(0);
    		ListNode greaterHead = new ListNode(0);
    		ListNode less = lessHead, greater = greaterHead;
    		ListNode node = head;
    		while(node != null)
    		{
    			ListNode temp = node.next;
    			if(node.val < x)
    			{
    				less.next = node;
    				less = less.next;
    				less.next = null;
    			}
    			else
    			{
    				greater.next = node;
    				greater = greater.next;
    				greater.next = null;
    			}
    			node = temp;
    		}
    		less.next = greaterHead.next;
    		return lessHead.next;
    	}
    
  • 相关阅读:
    sqlserver 分页
    sqlserver 用FOR XML PATH('')多行并成一列
    yarn的安装和使用
    redis安装及基本使用
    dbeaver 的界面乱码
    cypress测试框架(一)
    外网访问VMware虚拟机的Web服务---系列操作
    将博客搬至CSDN
    textgrid-python模块基础使用
    opencv通过mask掩码图合成两张图
  • 原文地址:https://www.cnblogs.com/masterlibin/p/5804432.html
Copyright © 2011-2022 走看看