LeetCode—面试题:分割链表(头插法)

分割链表(中等)

2020年10月1日

题目来源:力扣

在这里插入图片描述

解题

  • 头插法
    遍历找到比x小的节点,然后用后面的节点覆盖此节点,把该节点插到最前面
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    public ListNode partition(ListNode head, int x) {
    
    
        if(head==null) return null;
        ListNode tmp_head=head;
        while(tmp_head.next!=null){
    
    
            if(tmp_head.next.val<x){
    
    
                ListNode tmp=tmp_head.next;
                tmp_head.next=tmp_head.next.next;
                tmp.next=head;
                head=tmp;
            }else{
    
    
                tmp_head=tmp_head.next;
            }
        }
        return head;
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41541562/article/details/108893724