问题描述:假设有一个没有头指针的单链表。一个指针指向此单链表中间的一个节点(不是第一个,也不是最后一个节点),请将该节点从单链表中删除。
扩展问题
编写一个函数,给定一个链表的头指针,要求只遍历一次,将单链表中的元素顺序反转过来。
一般链表的删除需要顺着头结点向下找到当前待删节点的前驱节点,然后让前驱节点指向后驱节点就行了。这里,没有头结点,就没办法找到前驱结点。但我们可以采用“狸猫换太子”的做法。我们把当前结点“看成”是前驱结点,把后续节点当做待删结点删除(删除之前,记下后续结点的值),只需要让当前结点指向后驱结点的后驱结点。最后把后续结点值赋给当前结点的值。
- #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>
#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;
- }