单链表删除一个节点

有头结点的情况,附加一个逆置

#include <stdio.h>
#include <malloc.h>
#define null 0
typedef struct Node{
int value;
struct Node* next;
};

//尾插
void create(struct Node* head){
//p是工作指针
struct Node* p = head;
int i;
for(i = 1; i<=1; i++){

p->next = malloc(sizeof(struct Node));
p->next->value = i;
p->next->next = null;
p = p->next;

}
}

void print(struct Node* head){
struct Node* p = head->next;
while(p){
printf("%d\t",p->value);
p = p->next;
}
printf("\n");

}

int delete(struct Node* x,struct Node* head){
struct Node* p = head->next;
struct Node* pre = head;

while(p){
if(p->value == x->value){
pre->next = p->next;
free(p);
return 1;
}else{
pre = p;
}

p = p->next;
}

return 0;
}

void rev(struct Node* head){
if(head->next != null){
struct Node* p = head->next->next;
struct Node* temp;
struct Node* pre = head->next;
pre->next = null;
while(p){
temp = p;
p = p->next;
temp->next = pre;
pre = temp;
}
head->next = pre;
}
}

int main(int argc,char *argv[]){
struct Node* head = malloc(sizeof(struct Node));
head->value = -1;
create(head);
print(head);


struct Node* x = malloc(sizeof(struct Node));
x->value = 1;
delete(x,head);
print(head);


rev(head);
print(head);

return 0;
}



没有头结点的情况,还是有些不同的地方要注意的。

#include <stdio.h>
#include <malloc.h>
#define null 0
struct Node{
int value;
struct Node* next;
};

//头插
struct Node* create(){
struct Node* head = null;
int i;
for(i = 1; i<=10; i++){
if(head == null){
head = malloc(sizeof(struct Node));
head->value = i;
head->next = null;
}else{
struct Node* p = malloc(sizeof(struct Node));
p->value = i;
p->next = head->next;
head->next = p;
}
}
return head;
}

void print(struct Node* head){
struct Node* p = head;
while(p){
printf("%d\t",p->value);
p = p->next;
}
printf("\n");

}

//注意这里想改变head指针的指向 必须传head的引用 所以是 Node**
int delete(struct Node* x,struct Node** head){
struct Node* p = head;
struct Node* pre = head;
//被删除节点是第一个的时候要特殊处理
if((*head)->value == x->value ){
*head = (*head)->next;
free(p);
return 1;
}
while(p){
if(p->value == x->value){
pre->next = p->next;
free(p);
return 1;
}else{
pre = p;
}

p = p->next;
}

return 0;
}

int main(int argc,char *argv[]){

struct Node* head = create();
print(head);

struct Node* x = malloc(sizeof(struct Node));
x->value = 1;
delete(x,&head);
print(head);

return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值