趁着复习把课上的作业和代码上传上来嘿嘿嘿,这个系列的代码都是自己写的或者老师教学用的可能内存管理上有点小瑕疵,但是算法理解还是不错的!本系列所有代码在dev-cpp上可以跑通~
线性表的链式存储和基本操作:
#include <stdio.h>
#include <stdlib.h>
int m; //命令数
struct node{
int data;
struct node *next;
};
node *head; // head指向头节点
void insert(int i, int x){//插入x到a[i]
node*h=head;
node*n=h->next;
int k=1;
while(k!=i&&n!=NULL){
k++;
h=n;
n=n->next;
}
if(k==i){
node*nn=(node*)malloc(sizeof(node));
nn->data=x;
nn->next=n;
h->next=nn;
}
}
void deleteByIndex(int i){ //删除a[i]
node*h=head;
node*n=h->next;
int k=1;
while(k!=i&&n!=NULL){
k++;
h=n;
n=n->next;
}
if(k==i&&n!=NULL){
h->next=n->next;
free(n);
}
}
void find(int x){//查找第一个x
node*h=head->next;
int i=1;
while(h!=NULL){
if(h->data==x){
printf("%d\n",i);
return;
}
h=h->next;
i++;
}
printf("0\n");
}
void eliminateRepeat(){ //去除重复元素
node*h=head->next;
while(h!=NULL){
node*hh=h;
node*hhn=hh->next;
while(hhn!=NULL){
if(hhn->data==h->data){
hh->next=hhn->next;
free(hhn);
hhn=hh->next;
}
else{
hh=hhn;
hhn=hh->next;
}
}
h=h->next;
}
}
void count(int x, int y){//统计[x,y]中元素个数
int t=0;
node*h=head->next;
while(h!=NULL){
if(h->data>=x&&h->data<=y){
t++;
}
h=h->next;
}
printf("%d\n",t);
}
void deleteByRange(int x, int y){ //去除[x,y]范围内的元素
node*h=head;
node*n=h->next;
while(n!=NULL){
if(n->data>=x&&n->data<=y){
h->next=n->next;
free(n);
n=h->next;
}
else{
h=n;
n=h->next;
}
}
}
int main() {
scanf("%d", &m);
head = (node*) malloc(sizeof(node));
head->next = NULL;
for (int k = 0; k < m; k++){
int c, i, x, y;
scanf("%d", &c);
switch (c){
case 1: scanf("%d%d", &i, &x); insert(i, x); break;
case 2: scanf("%d", &i); deleteByIndex(i); break;
case 3: scanf("%d", &x); find(x); break;
case 4: scanf("%d%d", &x, &y); count(x, y); break;
case 5: eliminateRepeat(); break;
case 6: scanf("%d%d", &x, &y); deleteByRange(x, y); break;
}
}
return 0;
}
注意是带头结点的,这个就没什么难度了,可以自己画一下图:
带头指针就是头指针是不放东西的,好处就是判空和引用链表的时候比较方便,建议自己画一下。
这里比较难的可能就是插入和删除,需要两个指针,只要想明白你插入和删除都是要处理该位置前后的两个指针的,所以肯定需要一个记录的前驱指针,后继因为单链表特性就不用记录了。
还有可能比较容易出错的就是记得jd->next=xx才真的串起来了,不要直接拿个变量去串了。
总体来说其实单链表比顺序表简单很多,单链表的操作很方便,插入和删除顺序存储都是O(n),但单链表只要O(1)(看移动元素说得),不同的是顺序表的存储密度更大。