96 - 合并链表

xiaoxiao2021-02-27  162

5.5

果然一遇到链表,思路就很不清晰。

链表重点就是链表的维护问题。

比如我刚开始使用的flagS来直接修改,就会有错误。

其实应该修改的是flagS.next。

恩。。。。只可意会,不可言传。总之以后要用next来维护。

/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param head: The first node of linked list. * @param x: an integer * @return: a ListNode */ public static ListNode partition(ListNode head, int x) { // write your code here if(head == null || head.next == null){ return head; } ListNode newHead = new ListNode(0); newHead.next = null; //small用来标记最后一个小于x 的结点 ListNode flagS = newHead; //big用来标记最后一个大于等于x的结点 ListNode big = new ListNode(0); big.next = null; ListNode flagB = big; //flag用来标记当前链表中遍历到的点 ListNode flag = head; while(flag != null){ ListNode tmp = flag; flag = flag.next; tmp.next = null; if(tmp.val < x){ flagS.next = tmp; flagS = flagS.next; } else{ flagB.next = tmp; flagB = flagB.next; } } flagS.next = big.next; return newHead.next; } }

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

最新回复(0)