zoukankan      html  css  js  c++  java
  • 线性表——双向链表

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <ctime> 
    
    using namespace std;
    
    using ElemType = int;
    
    // 双向链表结点 
    class Node {
    public:
    	ElemType data;
    	Node *next;
    	Node *prior; 
    }; 
    
    // 初始化链表 
    void initList(Node *head, int n)
    {
    	srand(time(NULL));
    	Node *p = head, *r = head;
    	while (n--) {
    		Node *q = (Node*)malloc(sizeof(Node));
    		q->data = rand()%100 - 1;
    		p->next = q;
    		q->prior = p;
    		q->next = r;
    		r->prior = q;
    		p = q;
    	}
    }
    
    // 增加某结点 
    void addNode(Node *head, int i, ElemType val)
    {
    	int j = 0;
    	Node *p = head;
    	while (1) {
    		if (j == i - 1) {
    			Node *q = (Node*)malloc(sizeof(Node));
    			q->data = val;
    			q->prior = p;
    			q->next = p->next;
    			p->next->prior = q;
    			p->next = q;
    			break;
    		}
    		j++;			// p指向第j个结点 
    		p = p->next;
    	}
    }
    
    // 删除某结点 
    void delNode(Node *head, int i)
    {
    	int j = 0;
    	Node *p = head;
    	while (1) {
    		if (j == i) {
    			p->prior->next = p->next;
    			p->next->prior = p->prior;
    			break;
    		}
    		j++;
    		p = p->next;
    	}
    }
    
    // 取某结点的值 
    void getNode(Node *head, int i)
    {
    	int j = 0;
    	Node *p = head;
    	while (1) {
    		if (j == i) {
    			cout << "第" << i << "个结点的值为:" << p->data << endl;
    			break;
    		}
    		j++;
    		p = p->next;
    	}	
    }
    
    // 打印双向链表 
    void print(Node *head)
    {
    	Node *p = head;
    	p = p->next;
    	while (p != head) {
    		cout << p->data << " ";
    		p = p->next;
    	}
    	cout << endl;
    }
    
    
    int main()
    {
    	Node *head = (Node*)malloc(sizeof(Node));
    	head->prior = head;
    	head->next = head;
    	initList(head, 5);
    	print(head);
    	addNode(head, 2, 100);
    	print(head);
    	delNode(head, 2);
    	print(head);
    	getNode(head, 2);
    }
    

      

  • 相关阅读:
    Mongodb 插入数据的方式
    vue插槽(slot)的模板与JSX写法
    vue-resource+iview上传文件取消上传
    封装全局icon组件 svg (仿造element-ui源码)
    vue 修改框架less变量
    vue webpack多页面构建
    vue2 自定义全局组件(Loading加载效果)
    制作npm插件vue-toast-m实例练习
    iview+axios实现文件取消上传
    CSS Variables
  • 原文地址:https://www.cnblogs.com/xzxl/p/8643001.html
Copyright © 2011-2022 走看看