顺序表插入
#include<stdio.h>
#include<stdlib.h>
#define Maxsize 10
//定义顺序表
typedef struct {
int data[Maxsize];
int length;
}SeqList;
//顺序表的初始化
void InitList(SeqList& L)
{
L.length = 0;
}
//插入一个元素
void ListInsert(SeqList& L,int i,int e)//在i(表示位序)的位置,插入元素e
{
for (int j = L.length; j >= i; j--)//将位置为3以后的元素整体向后移动一个位置
{
L.data[j] = L.data[j - 1];
}
L.data[i - 1 ]= e;//这里需要注意下表和位序的关系,下标是从0开始,位序是从1开始
L.length++;//插入一个元素后,数组整体长度加一
}
int main()
{
SeqList L;
InitList(L);
ListInsert(L, 3, 3);
return 0;
}
顺序表的删除
#include<stdio.h>
#include<stdlib.h>
#define Maxsize 10
//定义顺序表
typedef struct {
int data[Maxsize];
int length;
}SeqList;
//顺序表的初始化
void InitList(SeqList& L)
{
L.length = 0;
}
//删除一个元素
bool ListDelete(SeqList& L,int i,int &e)//注意:必须有引用符号,才会实现真正意义上e的改变,否则我们进行的一系列操作都是其复制品,值实质并没有发生改变
{
if (i<1 || i>L.length)//判断i的范围是否有效
return false;
e=L.data[i-1];//返回删除元素的值
for (int j = i; j <L.length; j++)//依次向前移动
{
L.data[j-1] = L.data[j];
}
L.length--;
return true;//有效插入,返回true
}
int main()
{
SeqList L;
int e=-1;//定义和数组中元素类型相同的变量,作用:将删除的元素“带回”
InitList(L);
if(ListDelete(L,3,e))//判断ListDelete函数的返回值
printf("已经删除第三个元素,删除元素值为=%d\n",e);
else
printf("位序i不合法,删除失败\n");
return 0;
}
顺序表的查找
静态分配方式
#define Maxsize 10
typedef struct {
ElemType data[Maxsize];
int length;
}SqList;
ElemType GetElem(SqList L,int i)
{
return L.data[i-1];
}
动态分配方式
#define InitSize 10
typedef struct
{
ElemType*data;//动态分配数组的指针,该指针指向顺序表中的第一个元素
int Maxsize;
int length;
}SeqList;
ELemType GetElem(SeqList L,int i)
{
return L.data[i-1];
}
ElemType*data
链表插入 两种插入法
class Node{
public int data;
public Node next=null;
Node(int data){
this.data=data;
}
}
public class LinkedList {
private Node head = null;
//头插法
public void addFirst(int data) {
Node node = new Node(data);
if (head == null) {
head = node;
return;
}
node.next = head;
head = node;
}
//尾插法
public void addLast(int data) {
Node node = new Node(data);
if (head == null) {
head = node;
return;
}
Node tail = head;
while (tail.next != null) {
tail = tail.next;
}
tail.next = node;
}
—
链表删除操作
class Node{
public int data;
public Node next=null;
Node(int data){
this.data=data;
}
}
public class LinkedList {
private Node head = null;
public void remove(int toRemove) {
if (head.data == toRemove) {
head = head.next;
return;
}
Node prev = searchPrev(toRemove);
Node toDelete = prev.next;
prev.next = toDelete.next;
}
private Node searchPrev(int toRemove) {
for (Node cur = head; cur != null && cur.next != null; cur = cur.next) {
if (cur.next.data == toRemove) {
return cur;
}
}
return null;
}
链表查找
class Node{
public int data;
public Node next=null;
Node(int data){
this.data=data;
}
}
public class LinkedList {
private Node head = null;
public boolean contains(int toFind) {
for (Node cur = head; cur != null; cur = cur.next) {
if (cur.data == toFind) {
return true;
}
}
return false;
}
}