zoukankan      html  css  js  c++  java
  • LeetCode 面试题 02.04. 分割链表

    题目链接:https://leetcode-cn.com/problems/partition-list-lcci/ 

    编写程序以 x 为基准分割链表,使得所有小于 x 的节点排在大于或等于 x 的节点之前。如果链表中包含 x,x 只需出现在小于 x 的元素之后(如下所示)。分割元素 x 只需处于“右半部分”即可,其不需要被置于左右两部分之间。

    示例:

    输入: head = 3->5->8->5->10->2->1, x = 5
    输出: 3->1->2->10->5->5->8

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     struct ListNode *next;
     6  * };
     7  */
     8 
     9 struct ListNode* partition(struct ListNode* head, int x){
    10     if(head==NULL||head->next==NULL) return head;
    11     struct ListNode *q=head,*p=head;
    12     while(q){
    13         if(q->val<x){
    14             int tmp=q->val;
    15             q->val=p->val;
    16             p->val=tmp;
    17             p=p->next;
    18         }
    19         q=q->next;
    20     }
    21     return head;
    22 }
  • 相关阅读:
    autocare使用命令
    使用国内豆瓣源
    HCNA(二)以太网的帧结构
    HCNA(一)网络传输介质
    Python
    Python
    Python
    Delphi
    HCNP
    Python
  • 原文地址:https://www.cnblogs.com/wydxry/p/12400468.html
Copyright © 2011-2022 走看看