题目:Given an array nums
, write a function to move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12]
, after calling your function, nums
should be [1, 3, 12, 0, 0]
.
解答:用linklist来做,用两个头指针来指向0开头和不是0开头的链表,最后连起来。
#include <iostream> using namespace std; /** * Definition for singly-linked list.*/ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode* init(int a[], int n){ ListNode* q = NULL, *head = NULL; for(int i = 0; i < n; i++){ ListNode* p = new ListNode(0); p->val = a[i]; if(i==0){//不要忽略头结点的赋值 head = q = p; continue; } q->next=p; q = q->next; } q->next = NULL; return head; } ListNode* move_zero(ListNode* head){ ListNode* p = head, *q = head, *r = head, *s = head;//p denote the moving point, r is the head of zero bool zero = false; //用bool标记是否是开头,我觉得挺好用的 bool h = false; while(p != NULL){ if(p->val == 0){ if(zero == false){ r = p; s = r; zero = true; }else{ s->next = p; s = s->next; } }else{ if(h == false){ head = p; q = p; h = true; }else{ q->next = p; q = q->next; } } p = p->next; } q->next = r; s->next = NULL; return head; } void prints(ListNode* head){ while(head){ cout<<head->val<<" "; head = head->next; } } int main(int argc, const char * argv[]) { //int a[]={2,5,3,7,9,4,1,8}; int a[]={0, 1, 0, 3,12}; ListNode* head =new ListNode(0); head=init(a,5); ListNode* L = move_zero(head); prints(L); return 0; }
测试用例:
输入:
0, 1, 0, 3, 12
输出:
1 3 12 0 0
2.数组版本
这里用他人更简短的代码
void moveZeroes(vector<int>& nums) { int j = 0; for(int i = 0; i < nums.size(); i++) { if(nums[i] != 0) { int temp = nums[j]; nums[j] = nums[i]; nums[i] = temp; j++; } } }