链表分割

来源:互联网 发布:淘宝网安全中心在哪里 编辑:程序博客网 时间:2024/09/21 09:24

题目描述

编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前
给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。

java实现

import java.util.*;/*public class ListNode {    int val;    ListNode next = null;    ListNode(int val) {        this.val = val;    }}*/public class Partition {    public ListNode partition(ListNode pHead, int x) {        // write code here        if(pHead==null||pHead.next==null) return pHead;        ListNode smallList = new ListNode(-1);        ListNode bigList = new ListNode(-1);        ListNode s = smallList;        ListNode b = bigList;        ListNode head = pHead;        while (head!=null)        {            if(head.val<x)            {                s.next = head;                s = s.next;            }            else            {                b.next = head;                b = b.next;            }            head = head.next;        }        b.next = null;        s.next = bigList.next;        return smallList.next;    }}

C/C++ 实现

/*struct ListNode {    int val;    struct ListNode *next;    ListNode(int x) : val(x), next(NULL) {}};*/class Partition {public:    ListNode* partition(ListNode* pHead, int x) {        // write code here        if(pHead==NULL||pHead->next==NULL)return pHead;        ListNode* head1=new ListNode(0) ;          //一定要记得新建ListNode(指针链表)对象,不能只声明一个ListNode指针类型变量、即为空指针,        //否则 段错误:您的程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)等情况引起        ListNode* head2=new ListNode(0)  ;                        //    运行错误:请检查是否存在数组越界非法访问,野指针乱访问,空指针乱访问等情况        ListNode* head=pHead;        ListNode* mvhead1=head1;        ListNode* mvhead2=head2;        while(head!=NULL)            {            if(head->val<x){                mvhead1->next=head;                mvhead1=mvhead1->next;            }            else{                mvhead2->next=head;                mvhead2=mvhead2->next;            }            head=head->next;        }//while        mvhead2->next=NULL;        mvhead1->next=head2->next;        return head1->next;    }};
0 0
原创粉丝点击