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;
    	}
    
  • 相关阅读:
    一点创业想法
    【转】Java程序员常用工具类库
    向着高薪前进
    web开发可不可以是这样的?
    java 读取文本文件超简单的方法
    java操作xml超简单的方法
    Dijkstra算法
    ubuntu linux下如何配置ip地址以及DNS
    有关于string的一些用法
    Linux mint 17.2 系统下安装hust oj
  • 原文地址:https://www.cnblogs.com/masterlibin/p/5804432.html
Copyright © 2011-2022 走看看