链表
来源:互联网 发布:淘宝关键词怎么刷 编辑:程序博客网 时间:2024/06/07 00:29
struct Node {
char data;
Node* next;
};
Node* createList(char data[], int n) {
Node* head = (Node*) malloc(sizeof(Node));
Node* p = head;
for (int i = 0; i < n; i++) {
Node* node = (Node*) malloc(sizeof(Node));
node->data = data[i];
p->next = node;
p = p->next;
}
p->next = NULL;
return head;
}
void showList(Node* head) {
Node* p = head->next;
while (p != NULL) {
cout << p->data;
p = p->next;
}
cout << endl;
}
void myfree(Node* head) {
/*Node* p1=head->next;
Node* p2;
while(p1!=NULL){
cout<<p1->data;
p2=p1->next;
free(p1);
p1=p2;
}*/
Node* p1 = head;
Node* p2;
while (p1->next != NULL) {
if (p1 != head) {
cout << p1->data;
}
p2 = p1->next;
free(p1);
p1 = p2;
}
cout << p1->data;
free(p1);
}
int insert(Node* head, int pos, char e) {
int i = 0;
Node* p = head;
while (i != pos - 1 && p != NULL) {
i++;
p = p->next;
}
if (p == NULL) {
return -1;
}
Node* node = (Node*) malloc(sizeof(Node));
node->data = e;
Node* n = p->next;
p->next = node;
node->next = n;
return 1;
}
void del(Node* head,int pos)
{
int i=0;
Node* p=head;
while(i!=pos-1&&p!=NULL){
i++;
p=p->next;
}
Node* n=p->next;
p->next=p->next->next;
free(n);
}
//反转
void mreverse(Node* node)
{
if(node->next!=NULL)
{
Node* p1,*p2,*p3;
p1=node->next;
p2=p1->next;
p3=p2->next;
p1->next=NULL;
while(p3!=NULL){
p2->next=p1;
p1=p2;
p2=p3;
p3=p3->next;
}
p2->next=p1;
node->next=p2;
}
}
void mreverse2(Node* node)
{
Node* p1,*p2;
p1=node->next;
p2=p1->next;
while(p2!=NULL)
{
p1->next=p2->next;
p2->next=node->next;
node->next=p2;
p2=p1->next;
}
}
int main() {
char a[] = { 'a', 'b', 'c', 'd' };
Node* head = createList(a, 4);
insert(head, 1, 'g');
del(head,2);
mreverse(head);
mreverse2(head);
myfree(head);
return 0;
}
0 0
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- 链表
- pinvred
- 分页函数优化注意点(一):关注业务数据
- c语言常见函数自编写
- 有一行电文,已按下面规律译成密码
- 单片机汇编指令中RETI和RET的区别
- 链表
- django的安装
- 华为机试—整形数组异集
- shell学习三十天----break,continue,shift,getopts
- 在Linux-0.11中实现基于内核栈切换的进程切换
- 51单片机汇编指令详解
- 编一程序,将两个字符串连接起来,不要用strcat函数。
- AJAX——核心XMLHttpRequest对象
- MCS-51单片机存储器结构-特殊功能寄存器 :堆栈指针SP(Stack Pointer)