刪除單向鏈表中的某一個節點

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

已知一個單向鏈表的表頭head,寫出一個刪除某一個節點的算法,要求先找到此節點,而後刪除。ios

#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 9spa

相關文章
相關標籤/搜索