最近復習了線性表,對鏈表這一部分遺忘最大,所以手動實現一下單鏈表的增,刪,改,查,倒置等等加深理解,附上C++代碼:
#include<iostream> using namespace std; typedef struct LNode { //定義鏈表的結構 int data; struct LNode* next; }LNode,*LinkList; void create(LinkList& l) // 頭插法建立帶頭結點的鏈表,輸入小於0的數值視為終止 { l = (LinkList)malloc(sizeof(LNode)); int x; l->next = NULL; cin >> x; do { LNode* s = (LNode*)malloc(sizeof(LNode)); s->data = x; s->next = l->next; l->next = s; cin >> x; } while (x > 0); }
void tailCreate(linkList& l)
{
l = (linkList)malloc(sizeof(LNode));
int data;
l->next = NULL;
cin >> data;
linkList ptr = l;
while (data > 0)
{
linkList p = (linkList)malloc(sizeof(LNode));
p->data = data;
ptr->next = p;
p->next = NULL;
ptr = p;
cin >> data;
}
}
void dis(LinkList l) //輸出鏈表 { cout << "當前鏈表為:"<<endl; while (l->next != NULL) { cout << l->next->data << " "; l = l->next; } cout << endl; } LinkList insert(LinkList& l, int x) //頭插法插入結點在鏈表開頭 { LNode* s = (LNode*)malloc(sizeof(LNode)); s->data = x; s->next = l->next; l->next = s; return l; } int getNumber(LinkList l, int x)//按照值查找結點序號,返回序號 { int i = 0; while (l != NULL) { i++; if (l->data == x) { cout << "find x=" << x << " ,num=" << i - 1 << endl; break; } l = l->next; } return i; } LNode* getElement(LinkList l, int no)//按照序號查找結點並返回結點 { LNode* s = l->next; int j = 1; while (s->next != NULL && j < no) { s = s->next; j++; } cout <<"find No."<<no<<" is "<< s->data << endl; return s; } void delect(LinkList& l, int no)//刪除指定序號的節點 { if (no == 1) //因為第一個元素的前驅結點是頭結點,所以單獨處理刪除第一個元素的情況 { LNode* s = l; LNode* p = l->next; l->next = p->next; free(p); } else { LNode* s = getElement(l, no - 1); //先找到它的前驅結點 LNode* p; p = s->next; s->next = p->next; cout << "delect " << p->data << " success" << endl; free(p); } } void reverseList(LinkList& l) //將鏈表倒序 { LNode* s = (LNode*)malloc(sizeof(LNode)); LNode* p = (LNode*)malloc(sizeof(LNode)); s = l->next; l->next = NULL; while (s!= NULL) { p = s->next; s->next = l->next; l->next = s; s = p; } } int main(void) { LinkList l; int x, no; cout << "輸入正整數插入鏈表,輸入負整數后結束輸入:" << endl; create(l);//輸入鏈表 dis(l); //輸出鏈表 cout << "輸入要插入在鏈表前端的數值:" << endl; cin >> x; insert(l,x); dis(l); cout << "輸入要查找的結點數值:" << endl; cin >> x; getNumber(l,x);//根據數組查找第一個對應的結點 cout << "輸入要查找的結點序號(1~n):" << endl; cin >> no; getElement(l,no);//根據序號查找對應的數值 cout << "輸入要刪除的結點序號(1~n):" << endl; cin >> no; delect(l,no);//刪除指定序號的結點 dis(l); reverseList(l);//反轉鏈表 dis(l); }
執行上述程序的輸出如下: