首页 > 其他分享 >3.链表划分(Leetcode 86)

3.链表划分(Leetcode 86)

时间:2023-02-09 00:36:36浏览次数:50  
标签:head ListNode less ptr next 链表 86 Leetcode more

3.链表划分(Leetcode 86)
#include <stdio.h>
	
struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
    	ListNode less_head(0);
    	ListNode more_head(0);
    	ListNode *less_ptr = &less_head;
    	ListNode *more_ptr = &more_head;
        while(head){
        	if (head->val < x){
        		less_ptr->next = head;
        		less_ptr = head;
			}
			else {
				more_ptr->next = head;
				more_ptr = head;
			}
        	head = head->next;
        }
        less_ptr->next = more_head.next;
        more_ptr->next = NULL;
        return less_head.next;
    }
};

int main(){
	ListNode a(1);
	ListNode b(4);
	ListNode c(3);
	ListNode d(2);
	ListNode e(5);
	ListNode f(2);
	a.next = &b;
	b.next = &c;
	c.next = &d;
	d.next = &e;
	e.next = &f;	
	Solution solve;
	ListNode *head = solve.partition(&a, 3);	
	while(head){
		printf("%d\n", head->val);
		head = head->next;
	}
	return 0;
}

标签:head,ListNode,less,ptr,next,链表,86,Leetcode,more
From: https://www.cnblogs.com/Epiephany/p/17103835.html

相关文章

  • 4.反转链表 ||(Leetcode 92)
    4.反转链表||(Leetcode92)#include<stdio.h>structListNode{ intval; ListNode*next; ListNode(intx):val(x),next(NULL){}};classSolution{public:......
  • 5.复杂链表的深度拷贝(Leetcode 138)
    5.复杂链表的深度拷贝(Leetcode138) #include<stdio.h> structRandomListNode{ intlabel; RandomListNode*next,*random; RandomListNode(intx):label(x),......
  • 6.链表求环||(Leetcode 42)
    6.链表求环||(Leetcode42)方法一:#include<stdio.h>structListNode{ intval; ListNode*next; ListNode(intx):val(x),next(NULL){}};#include<set>cl......
  • 7.两个排序链表的交点(Leetcode 160)
    7.两个排序链表的交点(Leetcode160)方法一:#include<stdio.h>structListNode{ intval; ListNode*next; ListNode(intx):val(x),next(NULL){}};#include......
  • 8.翻转链表(Leetcode206)
    8.翻转链表(Leetcode206)#include<stdio.h>structListNode{ intval; ListNode*next; ListNode(intx):val(x),next(NULL){}};classSolution{public:......
  • 二分查找 Leetcode704
    1.二分查找(Leetcode704)题目:给定一个n(n在[1,10000]之间)个元素有序的(升序)整型数组nums和一个目标值target,写一个函数搜索nums中的target,如果目标值存在返回下标,否......
  • 在排序数组中查找元素的第一个和最后一个位置(Leetcode34)
    3.在排序数组中查找元素的第一个和最后一个位置(Leetcode34)给定一个按照升序排列的整数数组nums,和一个目标值target。找出给定目标值在数组中的开始位置和结束位置。如......
  • 插入搜索位置(Leetcode35)
    给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。你可以假设数组中无重复元素。题目解析:元素......
  • 链表基础
    二、链表:初识链表基础知识:什么是链表:链表是一种通过指针串联在一起的线性结构,每一个节点由两部分组成,一个是数据域一个是指针域(存放指向下一个节点的指针),最后一个节点......
  • 1.两个排序链表归并(Leetcode 21)
    1.两个排序链表归并(Leetcode21)#include<stdio.h>structListNode{ intval; ListNode*next; ListNode(intx):val(x),next(NULL){}};classSolution{p......