文章目录
- 题目
- 思路
- 代码
leetcode 86
题目
思路
左边一个往进插数字 ,右边一个往进插数字 ,整个队列都完了以后让左边的尾指针指向右边的头指针,将两个链表连起来再返回即可。
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
//head指的是当前节点
//next用来记住当前节点的下一个 防止丢失
ListNode leftHead = null,leftTail = null;
ListNode rightHead = null,rightTail = null;
ListNode next = null;
//在当前list上进行操作,不是新建,不存在浪费空间
while(head != null){
next = head.next;
head.next = null;
if(head.val < x){
if(leftHead == null){
leftHead = head;
}else{
leftTail.next = head;
}
leftTail = head;
}else{
if(rightHead == null){
rightHead = head;
}else{
rightTail.next = head;
}
rightTail = head;
}
head = next;
}
if(leftHead == null){
return rightHead;
}
leftTail.next = rightHead;
return leftHead;
}
}