在單鏈表中刪除指定值的節點


【說明】:

  本文是左程雲老師所著的《程序員面試代碼指南》第二章中“在單鏈表中刪除指定值的節點”這一題目的C++復現。

  本文只包含問題描述、C++代碼的實現以及簡單的思路,不包含解析說明,具體的問題解析請參考原書。

  感謝左程雲老師的支持。

【題目】:

  給定一個鏈表的頭節點 head 和一個整數 num,請實現函數將值為 num 的節點全部刪除。

  例如,鏈表為 1->2->3->4->NULL,num=3,鏈表調整后為:1->2->4->NULL。

 【思路】:

  解法:注意頭節點的處理。

【編譯環境】:

  CentOS6.7(x86_64)

  gcc 4.4.7

 【實現】:

  實現及測試代碼:

 1 /*
 2  *文件名:list_remove.cpp
 3  *作者:
 4  *摘要:在單鏈表中刪除指定值的節點
 5  */
 6 
 7 #include <iostream>
 8 
 9 using namespace std;
10 
11 class Node
12 {
13 public:
14     Node(int data)
15     {
16         value = data;
17         next = NULL;
18     }
19 public:
20     int value;
21     Node *next;
22 };
23 
24 Node* removeNode(Node *head,int num)
25 {
26     Node *cur = NULL;
27     while(NULL != head)
28     {
29         if(num != head->value)
30             break;
31         cur = head;
32         head = head->next;
33         delete cur;
34     }
35     
36     cur = head;
37     Node *pre = head;
38     while(NULL != cur)
39     {
40         if(num == cur->value)
41         {
42             pre->next = cur->next;
43             delete cur;
44         }
45         else
46         {
47             pre = cur;
48         }
49         cur = pre->next;
50     }
51     return head;
52 }
53 
54 void printList(Node *head)
55 {
56     while(NULL != head)
57     {
58         cout << head->value << " ";
59         head = head->next;
60     }
61     cout << endl;
62 }
63 
64 int main()
65 {
66     Node *head = NULL;
67     Node *ptr = NULL;
68     
69     for(int i =1;i<7;i++)//構造鏈表
70     {
71         if(NULL == head)
72         {    
73             head = new Node(i);
74             ptr = head;
75             continue;
76         }
77         ptr->next = new Node(i);
78         ptr = ptr->next;
79         ptr->next = new Node(i);
80         ptr = ptr->next;    
81     }
82     cout << "before remove:" << endl;
83     printList(head);
84     cout << "after remove:" << endl;
85     head = removeNode(head,2);    
86     printList(head);
87     return 0;
88 }
View Code

 

注:

  轉載請注明出處;

  轉載請注明源思路來自於左程雲老師的《程序員代碼面試指南》。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM