赞
踩
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成。
首先,本文主要将链表的操作分为三个部分,即创建链表,删除节点以及增加节点。其中链表的结构体定义以及函数声明与主函数如下:
typedef struct ListNode {
double value;
ListNode* next;
}ListNode;
ListNode* CreateList();
ListNode* DeleteNode(ListNode*);
ListNode* InsertNode(ListNode*);
创建头结点,并根据输入内容增加节点值。
提示:需要注意的是,此处使用while (cin>>Inputnum)作为循环判断条件,在函数最后必须清除cin缓冲区以继续后续输入。
ListNode* CreateList() { cout << "Input ListNode:" << endl; int Inputnum ; ListNode* head, * nodetemp, * node; head = nullptr; nodetemp = nullptr; while (cin>>Inputnum) { node = new ListNode; node->value = Inputnum; if (head == nullptr) { head = node; } else{ nodetemp->next = node; } nodetemp = node; nodetemp->next = nullptr; } cin.clear(); cin.ignore(); return head; }
链表的节点删除包含指针操作,以防断链。
ListNode* DeleteNode(ListNode* head) { int locate; cout << "Input delete location: " << endl; cin >> locate; if (locate == 1) { head = head->next; } else { ListNode* temp; temp = head; for (int i = 1; i < locate-1; i++) { temp = temp->next; } temp->next = temp->next->next; } return head; }
节点的插入同样包含指针操作,同时要判断插入位置的合法性。
ListNode* InsertNode(ListNode* head) { int locate; ListNode* insertnode = new ListNode; insertnode->next = nullptr; cout << "Input insert location: " << endl; cin >> locate; cout << "Input insert node: " << endl; cin >> insertnode->value; if (locate == 1) { insertnode->next = head; head = insertnode; } else { ListNode* temp; temp = head; for (int i = 1; i < locate - 1; i++) { temp = temp->next; } if (temp==nullptr) { cout << "illegal location!" << endl; exit(0); } else if (temp->next == nullptr) { temp->next = insertnode; } else { insertnode->next = temp->next; temp->next = insertnode; } } return head; }
最后,函数的主体与链表的打印。
int main() { ListNode* head, *count; head = CreateList(); PrintList(head); head = DeleteNode(head); PrintList(head); head = InsertNode(head); PrintList(head); return EXIT_SUCCESS; } void PrintList(ListNode* head) { ListNode* count; count = head; while (count != nullptr) { cout << count->value << " "; count = count->next; } cout << endl; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。