/* 链表 */
#include<stdio.h>
#include<stdlib.h>
int main()
{
//分配内存
int * p = (int*)malloc(sizeof(int));
free(p);
int * p = new int;
delete(p);
return 0;
};
struct node {//链表结点
int data;
node* next;
};
node* create(int a[], int l)//创造链表(数据数组, 数组长度)
{
node *p, *pre, *head;
head = new node;//新建头结点
head->next = NULL;
pre = head;//记录pre为head
for(int i=0;i<l;i++)
{
p = new node;//新建结点
p->data = a[i];
p->next = NULL;
pre->next = p;//前驱结点指向新建结点
pre = p;//移动,作为下个结点的前驱结点
}
return head;//返回头结点指针
};
node* createlink(int n)//创造一个长度为n的链表
{
node *head, *p, *pre;
head = new node;
head->next = NULL;
pre = head;
while(n--)
{
int data;
scanf("%d", &data);
p = new node;
p->data = data;
p->next = NULL;
pre->next = p;
pre = p;
}
return head;
}
int search(node* head, int x)//查找函数(头指针,要查找的数) ,返回要查找数的个数
{
int count = 0;
node *p = head->next; //要判断数据域时, 必须指向头指针的下一位(即第一个结点)
while(p != NULL)
{
if(p->data == x)
count++;
p = p->next;
}
return count;
};
void insert( node * head, int pos, int x)//在一个位置插入数(头指针, 插入位置, 插入数)
{
node *p = head;//记录p为head
for(int i=0;i<pos-1;i++) //位置下标-1
p = p->next;//i=0到首节点
//p到插入位置的前一个结点
node *q = new node;//新建结点
q->data = x;
q->next = p->next;//p q指向同一块区域
p->next = q;//p又指向新建结点q
};
void del( node * head, int x)//删除链表中所有为x的结点(头指针, 数)
{
node *p = head->next;
node *pre = head;//pre始终保持p的前驱结点的指针
while (p != NULL)//判断数据域
{
if(p->data == x)//找到数据域,删除该结点
{
pre->next = p->next;
delete(p);
p = pre->next;//p继续移到下一位
}
else//没有找到数据域,pre和p都后移一位
{
pre = p;
p = p->next;
}
}
};
void mergelink(node*a, node*b)//合并两个链表
{
node * tail = a;
while(tail->next != NULL)
{
tail=tail->next;
}
tail->next = b->next;
node* i = NULL;//有排序要求
node* j = NULL;
node t;
for(i = g1->next;i != NULL;i=i->next)//选择排序法
for(j=i->next;j != NULL;j=j->next)
{
if(i->id > j->id)
{
t.id = i->id;
t.score = i->score;
i->id = j->id;
i->score = j->score;
j->id = t.id;
j->score = t.score;
}
}
};
void printlink(node* c)//打印链表
{
c=c->next;
while(c != NULL)
{
printf("%d", c->data);
c=c->next;
}
};
void reprint(node * c)//打印反转链表(直接就是头结点)
{
while ( c != NULL)
{
printf("%d ", c->data);
c = c->next;
}
printf("\n");
};
node* reverse(struct node* head) //翻转链表
{
if( head == NULL || head->next == NULL)
return head;
node *p = NULL;
node *cur = head->next;
while( cur != NULL )
{
node *t = cur->next;
cur->next = p;
p = cur;
cur = t;
}
return p;
}
int main()
{
int a[6] = {1, 2, 4, 4, 5 ,6};
node * j = create(a, 6);//传过来头指针
insert(j, 4, 3);
printf("%d\n", search(j, 4));
j = j->next;
while (j != NULL)
{
printf("%d ", j->data);
j = j->next;
}
printf("\n");
return 0;
}
动态链表相关
最新推荐文章于 2024-07-25 11:35:59 发布