[LeetCode]86. Partition List

来源:互联网 发布:开心麻花网络剧 编辑:程序博客网 时间:2024/06/17 19:29

https://leetcode.com/problems/partition-list/

用两个链表分别保存大于等于和小于的节点,最后将两个链表相连并将large尾节点的下一节点置为空



/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode partition(ListNode head, int x) {        ListNode s = new ListNode(0);        ListNode l = new ListNode(0);        ListNode sp = s;        ListNode lp = l;        while (head != null) {            if (head.val < x) {                sp.next = head;                sp = sp.next;            } else {                lp.next = head;                lp = lp.next;            }            head = head.next;        }        sp.next = l.next;        lp.next = null;        return s.next;    }}


0 0
原创粉丝点击