[LeetCode] Partition List 分割单链表
来源:互联网 发布:保定网络托管 编辑:程序博客网 时间:2024/05/22 06:47
给你一个单链表和一个整数x,调整单链表的元素的位置,使得前半部分的值小于x,后半部分的值大于x。
下面的算法的思路和单链表快速排序的思路是一样的,该算法有可能改变节点的相对顺序。
ListNode *partition(ListNode *head, int x) { ListNode* slow = head; ListNode* fast = head; while(fast) { if(fast->val < x) // note the less-than-equal operator here // Input: 5->4->3 and x = 4 // Output: 4->3->5 { swap(slow->val, fast->val); slow = slow->next; } fast = fast->next; } return head;}
2. 下面的算法可以保持相对顺序不变。
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions. For example, Given 1->4->3->2->5->2 and x = 3, return 1->2->2->4->3->5.
思路很简单:先找出链表的长度和链表的尾节点,然后遍历链表,如果当前节点的值小于target,跳到下一个节点,如果当前节点的值大于等于target,则把这个节点移动到链表的末端。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *partition(ListNode *head, int x) { ListNode *p= new ListNode(0); p->next = head; head = p; // used to save the result head. ListNode *last=head; // used to get the last node if (head->next==NULL){return head->next;} int n=0; //length of the list while (last->next!=NULL){ last=last->next; n++; } //get the length and last node while (n>0){ // in case of non-stop loop, count n. if (p->next->val < x){ // val<x keep the node p=p->next; n--; }else{ // val>=x move to last last->next = new ListNode(p->next->val); // add node to the last last = last->next; p->next = p->next->next; //delete current node n--; } } return head->next; //the 1st node is elmininated }};
0 0
- [LeetCode] Partition List 分割单链表
- Leetcode Partition List 分割链表
- 【leetcode】【单链表】【86】Partition List
- leetcode:单链表之Partition List
- Partition List 分割链表
- LeetCode: Partition List
- LeetCode Partition List
- LeetCode: Partition List
- [Leetcode] Partition List **
- [Leetcode] Partition List
- [LeetCode] Partition List
- leetcode 81: Partition List
- [Leetcode] Partition List
- leetcode 118: Partition List
- [LeetCode]Partition List
- [leetcode]Partition List
- LeetCode-Partition List
- [leetcode] Partition List
- hibernate查询SQL语句返回自定义实体对象
- sqlserver 2008 安装完后无法为该请求检索数据
- 在groovy中如何使用Hibernate
- node.js httpserver 无法访问
- 给生活来一次傅立叶转换
- [LeetCode] Partition List 分割单链表
- mos的开关特性电压 关系
- Ubuntu Server安装VNC,实现VNC客户端远程登录Ubuntu Server界面,并安装Navicat
- Codility上的练习 (13)
- SquareLinearLayout(高等于宽的自适应LinearLayout)
- [LeetCode] Rotate Linked List
- Java虚拟机(六)-JVM性能优化
- .zip.001 .zip.002怎么用压缩包解压缩
- [LeetCode] k-th permutation 第k个排列