程序员面试金典——链表分割

    xiaoxiao2021-04-14  100

    题目描述

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

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

    解题思路:用两个链表,一个head放小于的,一个tail放大于等于的。然后将它们合并。

    注意代码中注释的地方,特别容易错误。

    import java.util.*; /* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Partition { public ListNode partition(ListNode pHead, int x) { // write code here ListNode tail = new ListNode(0); ListNode head = new ListNode(0); ListNode h = head; ListNode t = tail; while(pHead!=null){ if(x<=pHead.val){ tail.next = pHead; tail = tail.next; } else { head.next = pHead; head = head.next; } pHead = pHead.next; } head.next = t.next; //下句特别重要,不然尾巴后面的节点又会在原链表继续接上 tail.next = null; return h.next; } }

    转载请注明原文地址: https://ju.6miu.com/read-670481.html

    最新回复(0)