顺序表模拟实现及顺序表有关oj
一、顺序表模拟实现
#include "SeqList.h"
void SLInit(SL *ps) {
assert(ps);
ps->a = NULL;
ps->size = ps->capacity = 0;
}
void SLCheckCapacity(SL* ps) {
assert(ps);
if (ps->size == ps->capacity)
{
int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
SLDataType* tmp = realloc(ps->a, newCapacity * sizeof(SLDataType));
if (tmp == NULL)
{
printf("relloc fail\n");
exit(-1);
}
ps->a = tmp;
ps->capacity = newCapacity;
}
}
void SLDestory(SL* ps) {
assert(ps);
if (ps->a)
{
free(ps->a);
ps->a = NULL;
ps->capacity = ps->size = 0;
}
}
void SLPushBack(SL* ps, SLDataType x) {
assert(ps);
SLCheckCapacity(ps);
ps->a[ps->size++] = x;
}
void SLPopBack(SL* ps) {
assert(ps);
/*if (ps->size == 0)
{
printf("顺序表为空");
return;
}*/
assert(ps->size > 0);
ps->size--;
}
void SLPushFront(SL* ps, SLDataType x) {
SLInsert(ps, 0, x);
}
void SLPopFront(SL* ps) {
SLErase(ps, 0);
}
void SLInsert(SL* ps, int pos, SLDataType x) {
assert(ps);
assert(pos >= 0 && pos <= ps->size);
SLCheckCapacity(ps);
int end = ps->size - 1;
while (end >= pos)
{
ps->a[end + 1] = ps->a[end];
end--;
}
ps->a[pos] = x;
ps->size++;
}
void SLErase(SL* ps, int pos) {
assert(ps);
assert(pos >= 0 && pos < ps->size);
int begin = pos;
while (begin < ps->size - 1)
{
ps->a[begin] = ps->a[begin + 1];
begin++;
}
ps->size--;
}
int SLFind(SL* ps, SLDataType x) {
assert(ps);
for (int i = 0; i < ps->size; i++) {
if (ps->a[i] == x)
{
return i;
}
}
return -1;
}
void SLModifty(SL* ps, int pos, SLDataType x) {
assert(ps);
assert(pos >= 0 && pos < ps->size);
ps->a[pos] = x;
}
void SLPrint(SL* ps){
assert(ps);
for (int i = 0; i < ps->size; i++)
{
printf("%d ", ps->a[i]);
}
printf("\n");
}
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef int SLDataType;
typedef struct SeqList {
SLDataType* a;
int size;
int capacity; //容量空间大小
}SL;
void SLInit(SL* ps);
void SLPrint(SL* ps);
void SLCheckCapacity(SL* ps);
void SLDestory(SL* ps);
//尾插
void SLPushBack(SL* ps, SLDataType x);
//头插
void SLPushFront(SL* ps, SLDataType x);
//尾删
void SLPopBack(SL* ps);
//头删
void SLPopFront(SL* ps);
//任意位置
void SLInsert(SL* ps, int pos, SLDataType x);
void SLErase(SL* ps, int pos);
//查找和修改
int SLFind(SL* ps, SLDataType x);
void SLModifty(SL* ps, int pos, SLDataType x);
二、相关oj
1、移除元素
class Solution {
public:
int removeElement(vector<int>& nums, int val)
{
if(nums.size() == 0)
{
return 0;
}
int left = 0;
int right = 0;
sort(nums.begin(),nums.end());
while(right < nums.size()&&nums[right] != val)
{
right++;
left++;
}
if(right == nums.size())
{
return left;
}
while(right < nums.size())
{
if(nums[right] != val)
{
swap(nums[right],nums[left++]);
}
right++;
}
return left;
}
};
2、合并两个有序数组
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n)
{
nums1.resize(m);
for(auto e:nums2)
{
nums1.push_back(e);
}
sort(nums1.begin(), nums1.end());
}
};
原文地址:https://blog.csdn.net/uvrdes56dd6/article/details/143500398
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!