Xóa phần tử có giá trị x (xuất hiện đầu tiên).

Các anh cho em hỏi về C++ với ạ:

  • Nếu xóa 1 phần tử trong mảng biết trước vị trí k:
for[i=k; i trả về found chính là vị trí xuất hiện đầu tiên của ký tự x trong chuỗi str. else => Không tồn tại ký tự x trong chuỗi str. int found = str.find["x"]; if[found != string::npos] => trả về found chính là vị trí xuất hiện đầu tiên của chuỗi x trong chuỗi str. else => Không tồn tại chuỗi x trong chuỗi str. int found = str.find["x", y, z]; if[found != string::npos] => trả về found chính là vị trí xuất hiện đầu tiên của chuỗi x lấy ra z ký tự và sẽ bắt đầu tìm kiếm từ vị trí y trong chuỗi str. else => Không tồn tại chuỗi x trong chuỗi str.

12 Likes

inext, và nhớ giải phóng bộ nhớ của node đã xóa.

Code C++ mẫu:

node *deleteHead[node *l]{ node *p = l; p = p->next; delete[l]; return p; }

Xóa phần tử cuối cùng trong danh sách liên kết đơn.

Để xóa phần tử cuối cùng trong listLinker ta cần tìm node của phần tử trước phần tử cuối và gán next của nó bằng NULL, cũng phải xóa bỏ vùng nhớ đã cấp phát cho node cuối cùng.

Code C++ mẫu:

node *deleteTail[node *l]{ node *p = l; while [p->next->next != NULL]{ p = p->next; } delete[p->next]; p->next = NULL; return l; }

Xóa phần tử ở vị trí khác đầu và cuối trong danh sách liên kết đơn:

Để xóa phần tử ở vị trí k ta cần phải tìm node p của phần tử k-1 và gán p->next = p->next->next như hình vẽ.

Code C++ mẫu:

node *deleteAt[node *l, int k]{ node *p = l; for [int i = 0; i < k-1; i++]{ p = p->next; } node *temp = p->next; p->next = p->next->next; delete[temp]; return l; }

Hướng dẫn bài tập.

Code mẫu:

Ngôn ngữ C++:

#include using namespace std; struct node{ int data; node *next; }; node *createNode[int x]{ node *temp = new node; temp->next = NULL; temp->data = x; return temp; } void printList[node *l]{ node *p = l; while [p != NULL]{ cout data next; } } node *addElement[node*p, int x]{ node *temp = createNode[x]; p->next = temp; return temp; } node *deleteHead[node *l]{ node *p = l; p = p->next; delete[l]; return p; } node *deleteTail[node *l]{ node *p = l; while [p->next->next != NULL]{ p = p->next; } delete[p->next]; p->next = NULL; return l; } node *deleteAt[node *l, int k]{ node *p = l; for [int i = 0; i < k-1; i++]{ p = p->next; } node *temp = p->next; p->next = p->next->next; delete[temp]; return l; } int main[]{ int n, x, k; cin >> n; cin >> x; node *l = createNode[x]; node *p = l; for [int i = 1; i < n; i++]{ cin >> x; p = addElement[p, x]; } cin >> k; if [k == 0]{ l = deleteHead[l]; } else if [k == n-1]{ l = deleteTail[l]; } else{ l = deleteAt[l, k]; } printList[l]; return 0; }

Video liên quan

Chủ Đề