zoukankan      html  css  js  c++  java
  • 线性表——链表实现(单链表)

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    
    using namespace std;
    
    using ElemType = int;
    
    // 单链表结构 
    class Node {
    public:
    	ElemType data;
    	Node *next;
    }; 
    
    
    // 初始化单链表 
    void initList(Node *head)
    {
    	char ch;
    	int val;
    	Node *q = head;
    	while(1) {
    		cout << "是否新增结点(y/n):";
    		cin >> ch;
    		if (ch == 'n') {
    			return;
    		}
    		cout << "请输入结点的值:";
    		cin >> val;
    		Node *p = (Node*)malloc(sizeof(Node));
    		p->data = val;
    		p->next = nullptr;		// 尾插法 
    		q->next = p;
    		q = p;
    	}
    }
    
    // add
    void addNode(Node *head, int i, ElemType val)
    {
    	Node *q = head;
    	int j = 0;
    	bool flag = false;
    	while (q->next != NULL)
    	{
    		if (j != i - 1) {
    			j++;
    			q = q->next;		// q指向第j个结点 
    		}
    		if (j == i - 1) {
    			flag = true;
    			Node *p = (Node*)malloc(sizeof(Node));
    			p->data = val;
    			p->next = q->next;
    			q->next = p;
    			break;
    		}
    	}
    	if (!flag) {
    		cout << "fail to add node
    ";
    		return;
    	}
    }
    
    // del
    void delNode(Node *head, int i)
    {
    	Node *q = head;
    	int j = 0;
    	bool flag = false;
    	while(q->next != NULL) {
    		if (j == i - 1) {
    			flag = true;
    			if (q->next->next == NULL) {
    				q->next = NULL;
    			}
    			else {
    				q->next = q->next->next;
    			}
    		}
    		j++;
    		q = q->next;
    	}
    	if (!flag) {
    		cout << "fail to del node
    ";
    		return;
    	}
    }
    
    void print(Node *head)
    {
    	Node *q = head;
    	while (q->next != NULL) {
    		q = q->next;
    		cout << q->data << " ";
    	}
    	cout << endl;
    }
    
    int main()
    {
    	Node *head = (Node*)malloc(sizeof(Node));
    	head->next = NULL;
    	initList(head);
    	print(head);
    	int i;
    	ElemType val;
    	cin >> i >> val;
    	addNode(head, i, val);
    	delNode(head, 1);
    	print(head);
    }
    

      

  • 相关阅读:
    framwork NHibernate
    java eclise的配置
    java jdk环境变量配置
    第零章 关于课程教材与讲义
    ActiveMQ(5.10.0)
    ActiveMQ(5.10.0)
    ActiveMQ(5.10.0)
    ActiveMQ(5.10.0)
    ActiveMQ(5.10.0)
    ActiveMQ(5.10.0)
  • 原文地址:https://www.cnblogs.com/xzxl/p/8642311.html
Copyright © 2011-2022 走看看