#include<stdio.h>
#include<stdlib.h>
typedef struct stu{
int n;
struct stu* next;
}node;
node* build(int n){
node *p1,*p2,*head;
head=p1=p2=(node*)malloc(sizeof(node));
int i=1;
while(n--){
p2=p1;
p1=(node*)malloc(sizeof(node));
p2->n=i++;
p2->next=p1;
}
free(p1);
p2->next=head;
return head;
}
void delete(node *head,int n){
int i=0;
node *pt=(node*)malloc(sizeof(node));
pt->n=0;
pt->next=head;
node *ph=head;
while(n>1){
i%=3;
if(i==2){
pt->next=ph->next;
free(ph);
ph=pt->next;
n--;
}
else {
ph=ph->next;
pt=pt->next;
}
i++;
}
printf("%d",pt->n);
}
int main(){
int n;
scanf("%d",&n);
node* circle=build(n);;
delete(circle, n);
}
当要删除节点时,一定要用两个指针,然后再给链表加一个哑结点,这样会方便很多,建立链表时要注意p1,p2连接和开辟空间的顺序
细节很重要