从无头单链表中删除节点

问题描述:假设有一个没有头指针的单链表。一个指针指向此单链表中间的一个节点(不是第一个,也不是最后一个节点),请将该节点从单链表中删除。

一般链表的删除需要顺着头结点向下找到当前待删节点的前驱节点,然后让前驱节点指向后驱节点就行了。这里,没有头结点,就没办法找到前驱结点。但我们可以采用“狸猫换太子”的做法。我们把当前结点“看成”是前驱结点,把后续节点当做待删结点删除(删除之前,记下后续结点的值),只需要让当前结点指向后驱结点的后驱结点。最后把后续结点值赋给当前结点的值。

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

typedef struct node{
	int data;
	node *next;
}Node;

void printlist(Node *head_ptr);
void delete_random_node(Node *current);

int main(){
	Node n1, n2, n3;
	n1.data = 10;
	n1.next = &n2;
	n2.data = 20;
	n2.next = &n3;
	n3.data = 30;
	n3.next = NULL;
	printf("Before deleting\n");
	printlist(&n1);
	delete_random_node(&n2);
	printf("\nAfter deleting\n");
	printlist(&n1);
	return 0;
}

void printlist(Node *head_ptr){  
    Node *ptr = head_ptr; 
    while(ptr != NULL){  
        printf("%d    ", ptr->data);  
        ptr = ptr->next;  
    }  
    printf("\n");  
}  

void delete_random_node(Node *current){
	assert(current != NULL);
	Node *next = current->next;
	if(next != NULL){
		current->next = next->next;
		current->data = next->data;
	}
}

 

扩展问题

编写一个函数,给定一个链表的头指针,要求只遍历一次,将单链表中的元素顺序反转过来。

#include<stdio.h>
#include<stdlib.h>

typedef struct node{
	int data;
	node *next;
}Node;

Node *reverse_linklist(Node *head);
void printlist(Node *ptr);

int main(){
	Node n1, n2, n3;
	Node *head;
	head = (Node *)malloc(sizeof(Node));
	head->next = &n1;
	n1.data = 10;
	n1.next = &n2;
	n2.data = 20;
	n2.next = &n3;
	n3.data = 30;
	n3.next = NULL;

	printf("Before reversing\n");
	printlist(head);
	printf("\nAftering reversing\n");
	printlist(reverse_linklist(head));
	return 0;
}

void printlist(Node *head_ptr){
	Node *ptr = head_ptr->next;
	while(ptr != NULL){
		printf("%d    ", ptr->data);
		ptr = ptr->next;
	}
	printf("\n");
}

Node *reverse_linklist(Node *head){
	Node *p = head->next;
	Node *e = NULL;
	Node *q;
	while(p->next != NULL){
		q = p->next;
		p->next = e;
		e = p;
		p = q;
	}
	p->next = e;
	head->next = p;
	return head;
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值