zoukankan      html  css  js  c++  java
  • 删除单向链表中的某一个节点

    原文链接:http://blog.csdn.net/huahuahailang/article/details/8762785

    已知一个单向链表的表头head,写出一个删除某一个节点的算法,要求先找到此节点,然后删除。

    #include <iostream>
    
    using namespace std;
    
    typedef struct node
    {
    	int number;
    	struct node *next;
    }Node;
    
    Node *Delete(Node *head, int key){
    	Node *node1 = head;
    	Node *node2 = NULL;
    	if(head == NULL){
    		return NULL;
    	}
    	else{
    		if(node1->number == key){
    			head = head->next;
    			free(node1);
    			return head;
    		}
    		else{
    			while(node1 != NULL){
    				node2 = node1;
    				node2 = node1 -> next;
    				if(node2 -> number == key){
    					node1 -> next = node2 -> next;
    					free(node2);
    					break;
    				}
    				node1 = node1 -> next;
    			}
    			return head;
    		}
    	}
    }
    
    int main(){
    
    	Node *head = (Node*)malloc(sizeof(Node));
    	Node *p, *q, *q1;
    	int key;
    	p = (Node*)malloc(sizeof(Node));
    	q1 = q = head;
    	int i;
    	for(int i = 1; i < 10; i++){
    		p -> number = i;
    		head -> next = p;
    		head = p;
    		p = (Node*)malloc(sizeof(Node));	
    	}
    	head -> next = NULL;
    	cout << "原链表数据:" << endl;
    	q1 = q1 -> next;
    	while(q1 != NULL){
    		cout << q1 -> number << " ";
    		q1 = q1 -> next;
    	}
    	cout << endl;
    	cout << "输入要删除的数据:";
    	cin >> key;
    	p = Delete(q -> next, key);
    	cout << "删除一个" << key << "之后的链表数据:"	<< endl;
    	while(p != NULL){
    		cout << p -> number << " ";
    		p = p ->next;
    	}
    	cout << endl;
    	free(p);
    	free(head);
    	return 0;
    }
    

      程序运行结果:

    原链表数据:
    1 2 3 4 5 6 7 8 9
    输入要删除的数据:5
    删除一个5之后的链表数据:
    1 2 3 4 6 7 8 9

     
     
     
  • 相关阅读:
    定时器
    Eclipse 启动时闪退问题解决方案
    VMware下安装centos6.7的步骤
    bin/mysqld: error while loading shared libraries: libnuma.so.1: 安装mysql
    CentOS系统bash: groupadd: command not found问题
    MyBatis Sql语句中的转义字符
    Postgresql 正则表达式
    JS生成GUID方法
    jqGrid 事件
    jqgrid 事件说明
  • 原文地址:https://www.cnblogs.com/gatherstars/p/8196203.html
Copyright © 2011-2022 走看看