题解 | #链表分割#

链表分割

http://www.nowcoder.com/practice/0e27e0b064de4eacac178676ef9c9d70

/* struct ListNode { int val; struct ListNode next; ListNode(int x) : val(x), next(NULL) {} };/ class Partition { public: ListNode* partition(ListNode* pHead, int x) { //1创建指针4个,和链表遍历指针cur ListNode* bigTail,bigHead,smallTail,smallHead; bigHead=bigTail=(ListNode)malloc(sizeof(ListNode)); smallHead=smallTail=(ListNode)malloc(sizeof(ListNode)); ListNode cur=pHead; //2.遍历链表,处理边界情况 if(cur==NULL) return NULL; else if(cur->next==NULL) return pHead; while(cur) { if(cur->val>=x) { bigTail->next=cur; bigTail=cur; } else { smallTail->next=cur; smallTail=cur; } cur=cur->next; } //3.连接链表,处理可能成环情况 smallTail->next=bigHead->next; bigTail->next=NULL; ListNode* head=smallHead->next; free(bigHead); free(smallHead); return head; } };

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务