/*除了删除链表倒数的n个操作外还加了些常见操作
思路:利用快慢指针,先让快指针走n+1步,再同时一步步移动快慢指针,直到快指针指向null,此时慢指针的下个指针就是要删除的位置
*/
#include<stdio.h>
#include<stdlib.h>
struct Mylinkedlist
{
int val;
struct Mylinkedlist* next;
} ;
typedef struct Mylinkedlist Mylinkedlist;
//1.初始化链表
Mylinkedlist* Initlist()
{
Mylinkedlist*head=(Mylinkedlist*)malloc(sizeof(Mylinkedlist));
if(head==NULL)
{
┊ perror("head");
}
head->next=NULL;
return head;
}
//2.头部插入
void myLinkedListAddAtHead(Mylinkedlist*head,int val)
{
Mylinkedlist* new=(Mylinkedlist*)malloc(sizeof(Mylinkedlist));
if(new==NULL)
{
┊ perror("new");
}
new->next=head->next;
head->next=new;
new->val=val;
}
//3.尾部插入
void MylinkedlistAddattail(Mylinkedlist*head,int val)
{
Mylinkedlist* new=(Mylinkedlist*)malloc(sizeof(Mylinkedlist));
if(new==NULL)
{
┊ perror("new");
}
Mylinkedlist *p=head;
while(p->next!=NULL)
{
┊ p=p->next;
}
p->next=new;
new->val=val;
new->next=NULL;
}
//4.任意位置插入
void MylinkedlistAddatindix(Mylinkedlist*head,int indix,int val)
{
Mylinkedlist* new=(Mylinkedlist*)malloc(sizeof(Mylinkedlist));
if(new==NULL)
{
┊ perror("new");
}
Mylinkedlist*p=head;
while(indix--)
{
┊ p=p->next;
}
new->next=p->next;
p->next=new;
new->val=val;
}
//5.删除第n个节点
void Mylinkedlistdelete(Mylinkedlist*head,int indix)
{
Mylinkedlist*p=head;
Mylinkedlist*tmp=NULL;
while(indix--)
{
┊ tmp=p;
┊ p=p->next;
}
tmp->next=p->next;
free(p);
}
//6.反转
Mylinkedlist*reverselist(Mylinkedlist*head)
{
Mylinkedlist*p=NULL;
Mylinkedlist*cur=head;
Mylinkedlist*tmp;
while(cur)
{
┊ tmp=cur->next;//保存下个
┊ cur->next=p;//把下个指向p
┊ p=cur;//移动tmp
┊ cur=tmp;//移动cur
}
while(p->next)
{
┊
printf("%d ",p->val);
p=p->next;
}
printf("\n");
return cur;
}
//7.打印链表
void printflist(Mylinkedlist*head)
{
Mylinkedlist*p=head;
while(p->next)
{
┊ p=p->next;
┊ printf("%d ",p->val);
}
printf("\n");
}
//8.删除倒数第n个元素
Mylinkedlist*removeNthFromEnd(Mylinkedlist* head, int n)
{
Mylinkedlist*fast=head;
Mylinkedlist*low=head;
for(int i=0;i<n+1;i++)
{
┊ fast=fast->next;
}
while(fast)
{
┊ fast=fast->next;
┊ low=low->next;
}
Mylinkedlist*del=low->next;
low->next=del->next;
free(del);
return head;
}
int main()
{
Mylinkedlist*ret= Initlist();
myLinkedListAddAtHead(ret,10);//头部插入
myLinkedListAddAtHead(ret,20);
myLinkedListAddAtHead(ret,30);
printflist(ret);//打印链表
removeNthFromEnd(ret,2);
printflist(ret);//打印链表
/*
// reverselist(ret);
MylinkedlistAddattail(ret,40);//尾部插入
MylinkedlistAddatindix(ret,3,60);//任意位置插入
printflist(ret);//打印链表
Mylinkedlistdelete(ret,1);//删除
printflist(ret);
reverselist(ret);//反转链表
*/
return 0;
}
199,1 Bot
02-24
1600
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)