扩展问题。
1.单链表从尾到头输出
解法1.用下面的rev,然后正向输出链表
解法2.用栈或者递归正向输出链表
比如用递归:
void fun(link* p){
if(p->next!=null){
fun(p->next);
}
printf("%d\t",p->value);
}
2.反向输出字符串
可以参照解法2.
void fun(char* s){
if(*s != '\0'){
fun(s+1);
}
printf("%c",*s);
}
3.给定待删除节点的指针,在o(1)时间删除节点。
p如果不是最后一个节点,就把p当作前驱,把p->next的数据域复制过来,然后就和普通删除一样了。p要是最后一个节点,就只能遍历找前驱了。
有头结点的情况,附加一个逆置
#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; }