下面简单的进行单链表的插入删除销毁等操作,想重点的说一下,关于链表插入的时候,分为三种情况,不过原理都一样。在尾插的时候,我们没有遍历链表,不清楚链表的长度,如何判断for循环如何终止呢?
由本人水平有限,有错误之处,请大家指正!
点击(此处)折叠或打开
-
- #include
- using namespace std;
- struct List {
-
-
- int data;
- struct List *next;
- };
-
-
- List *CreateFirst() {
-
-
- List *first;
- first = new List;
- first->next = NULL;
- return first;
- }
-
-
- List *InitialList(List *first) { //用尾插法创建链表,并赋值
-
-
- List *p, *head;
- head = first;
- /* 首插法创建链表
- for (int i = 0; i < 10; i++) {
- p = new List;
- p->data = i;
- p ->next = first ->next;
- first ->next = p;
-
- }**/
-
- for (int i = 0; i < 10; i++) {
- p = new List;
- p->data = i;
- head->next = p;
- head = p;
- head->next = NULL;
- }
- return first;
- }
-
-
- void PrintList(List *first) {
-
-
- do {
-
-
- first = first->next;
- cout << first->data << " ";
-
- } while (first != NULL);
- }
-
-
- int PrintLength(List *first) {
-
-
- int i = 0;
- for (List *q = first; q !=NULL ; q = q->next) {
-
-
- i++;
- }
- return i-1;
- }
-
-
- int Delete(List *first, int i) {
-
-
- List *s;
- int ddata;
- int count = 0;
- for (int j = 0; j < i - 1; j++) {
-
-
- first = first->next;
- count++;
- }
-
-
- s = first->next;
- ddata = (*s).data;
- first->next = s->next;
- delete s;
- return ddata;
- }
-
-
- void InsertList(List *first, int i, int x) {
-
-
- /* List *s; // 插入链表首部
- int ddata;
- s = new List;
- s->data = x;
- s->next = first->next;
- first->next = s; */
-
-
- /* List *s; //插入两结点之间
- int ddata;
- for (int j = 0; j < i - 1; j++) {
-
-
- first = first->next;
- }
- s = new List;
- s->data = x;
- s->next = first->next;
- first->next = s; */
-
-
- List *s; // 插入链表尾部
- int ddata;
- for (; first->next != NULL; first = first->next);
- s = new List;
- s->data = x;
- s->next = first->next;
- first->next = s;
-
- }
-
-
- void DestroyList(List *first) {
-
-
- while (first != NULL) {
- List *s;
- s = first;
- first = first->next;
- delete s;
- }
- }
- void main() {
-
-
- List *s, *t;
- s = CreateFirst();
- t = InitialList(s);
- cout << Delete(t, 3) << endl;
- //InsertList(t, 3, 11);
- PrintList(t);
- DestroyList(t);
-
- }
-
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29876893/viewspace-1814392/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/29876893/viewspace-1814392/