Em chào các anh chị,
Em có 1 bài tập là cho ntn.
struct LNode{
int ID; // giá trị khóa của con trỏ
struct LNode* tieptheo; // con trỏ trỏ đến nút kế tiếp
}
Đề bài: Lập trình hàm struct LNode* loaibo(struct LNode* h)
thực hiện loại bỏ nút cuối cùng của ds liên kết đơn có con trỏ đầu là h và trả về con trỏ đến đầu danh sách mới thu được bằng phương pháp đệ quy.
Đối với việc xóa bằng while thì em ok, nhưng xóa bằng đệ quy và trả về con trỏ đầu tiên thì em chưa làm được( Do không có ý tưởng)
Em gửi mã nguồn. Em viết trên Dev C++, anh em có thể sử dụng https://www.codechef.com/ide để code nhé.
Cám ơn mọi người giúp đỡ
#include <stdio.h>
#include <stdlib.h>
struct LNode{
int ID;
struct LNode* tieptheo;
};
struct LNode* init(){
struct LNode* head = (struct LNode*)malloc(sizeof(struct LNode*));
head = NULL;
return head;
}
struct LNode* createNode(int v){
struct LNode* newNode = (struct LNode*)malloc(sizeof(struct LNode*));
newNode->ID = v;
newNode->tieptheo = NULL;
return newNode;
}
// Insert
struct LNode* insertToHead(struct LNode* head, int v){
struct LNode* newNode = (struct LNode*)malloc(sizeof(struct LNode*));
newNode->ID = v;
newNode->tieptheo = head;
return newNode;
}
struct LNode* insertToLast(struct LNode* head, int v){
struct LNode* newNode = createNode(v);
if(head == NULL){
return insertToHead(head,v);
}else{
struct LNode* temp = head;
while(temp->tieptheo != NULL){
temp = temp->tieptheo;
}
temp->tieptheo = newNode;
return head;
}
}
// Delete
struct LNode* removeLast(struct LNode* head){
struct LNode* prev = NULL;
struct LNode* current = NULL;
current = head;
while(current->tieptheo != NULL){
prev = current;
current = current->tieptheo;
}
prev->tieptheo = NULL;
free(current);
return head;
}
// HAM XOA DE QUY
// EM KHONG CO Y TUONG
struct LNode* loaibo(struct LNode* head){
struct LNode* temp;
if(temp->tieptheo == NULL){
temp = NULL;
return head;
}else{
temp = loaibo(head->tieptheo);
head->tieptheo = temp;
return head;
}
}
void inDanhSach(struct LNode* head){
struct LNode* temp = head;
for(temp; temp!= NULL; temp = temp->tieptheo){
printf("i: %d\n",temp->ID);
}
}
int main(int argc, char *argv[]) {
struct LNode* head = init();
head = insertToLast(head, 1);
head = insertToLast(head, 3);
head = insertToLast(head, 3);
head = insertToLast(head, 4);
head = insertToLast(head, 8);
head = insertToLast(head, 5);
head = insertToLast(head, 15);
inDanhSach(head);
head = loaibo(head);
printf("------ AFTER REMOVE LAST----- \n");
inDanhSach(head);
return 0;
}