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;
    	}
    
  • 相关阅读:
    Servlet常用类
    Java库使用----xstream1.3.1
    字符串处理---统计每一行字符串当中的字符“u”个数
    读写锁
    求阶乘
    Fibonacci数列
    22.2-按照升序显示不重复的单词
    22.1-在散列集上进行集合操作
    完美世界-2015校园招聘-java服务器工程师-成都站
    运用jQuery写的验证表单
  • 原文地址:https://www.cnblogs.com/masterlibin/p/5804432.html
Copyright © 2011-2022 走看看