数据结构----链表
板子:
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct node
{ElemType data;struct node*next;//结构体类型的指针,用来存放下一个地址
}Node;//单链表-初始化
Node*initList()
{Node*head=(Node*)malloc(sizeof(Node));head->data=0;head->next=NULL;return head;
}
//头插法
int insertHead(Node*L,ElemType e)
{Node*p=(Node*)malloc(sizeof(Node));p->data=e;p->next=L->next;L->next=p;//存p的地址
}
//遍历
void listNode(Node*L)
{Node*p=L->next;//第一个节点(不是头节点)赋值给p指针 while(p!=NULL){printf("%d ",p->data);p=p->next;}
}
//尾插法
//获取尾节点位置
Node *get_tail(Node*L)
{Node*p=L;while(p->next!=NULL){p=p->next;}return p;}
//插入
Node *insertTail(Node*tail,ElemType e)
{Node*p=(Node*)malloc(sizeof(Node));p->data=e;tail->next=p;p->next=NULL;return p;//返回的是新的尾节点 }
//在任意位置插入
//传入链表,头节点
int insertNode(Node*L,int pos,ElemType e)
{Node*p=L;//创建p用来保存插入位置的前驱节点 int i=0;//i来记录所插入节点的前一个位置 while(i<pos-1){p=p->next;i++;if(p==NULL){return 0;}}//要插入的新节点Node*q=(Node*)malloc(sizeof(Node));q->data=e;q->next=p->next;p->next=q;return 1; }
//删除节点
int deleteNode(Node*L,int pos)
{Node*p=L;//创建p用来保存删除位置的前驱节点 int i=0;//i来记录所删除节点的前一个位置 while(i<pos-1){p=p->next;i++;if(p==NULL){return 0;}}if(p->next==NULL){printf("要删除的位置错误\n");return 0;}//创建q,指向要删除的节点 Node*q=p->next;p->next=q->next;free(q);//记得释放 return 1;
}
//获取链表长度
int listLength(Node*L)
{Node*p=L;int len=0;while(p!=NULL){p=p->next;len++; }return len;}
//释放链表:头节点不释放
void freeList(Node*L)
{Node*p=L->next;Node*q;while(p!=NULL){q=p->next;free(p);p=q;}L->next=NULL;
}
//查找倒数第k个节点
int findNodeFS(Node*L,int k)
{Node*fast=L->next;Node*slow=L->next;for(int i=0;i<k;i++){fast=fast->next;}while(fast!=NULL){fast=fast->next;slow=slow->next;}printf("倒数第%d个节点值为:%d\n",k,slow->data);
}
int main()
{Node*list=initList();Node*tail=get_tail(list);tail=insertTail(tail,10);tail=insertTail(tail,20);tail=insertTail(tail,30);listNode(list);insertNode(list,2,15);listNode(list);deleteNode(list,2);listNode(list);printf("%d\n",listLength(list));//freeList(list);//printf("%d\n",listLength(list));findNodeFS(list,1);
}
一、单链表应用
1.1
【使用双指针找到倒数第k个节点】:先让快指针多走k步,然后快慢指针同步走,快指针指向NULL的时候,慢指针就找到了
//查找倒数第k个节点
int findNodeFS(Node*L,int k)
{Node*fast=L->next;Node*slow=L->next;for(int i=0;i<k;i++){fast=fast->next;}while(fast!=NULL){fast=fast->next;slow=slow->next;}printf("倒数第%d个节点值为:%d\n",k,slow->data);
}
1.2
1.先分别求出两个链表的长度m和n
2.Fast指针指向较长的链表,先走m-n或者n-m步
3.同步移动指针,判断它们是否指向同一个节点