1. 程式人生 > >重拾C/C++ 使用Struct結構建立簡單的連結串列

重拾C/C++ 使用Struct結構建立簡單的連結串列

本次程式會用到的基本知識:

typedef: C/C++中的關鍵字的一種,用於給複雜的資料型別進行重新換名。  

例子:

typedef int km_per_hour ; 

//1. int current_speed;

 2.km_per_hour current_speed; 

其中 1中 和 2 中的current_speed 是同一種類型- int.

另外; 堆(heap)和棧(stack).

堆和棧都被儲存在隨機存取儲存器(RAM)中。在多執行緒中,各個執行緒都會被分配在各自的堆中,但是不同執行緒之間分享棧。這就是為什麼不同執行緒不能同時訪問棧。

當我們在函式總建立一個新的物件的時候(like, int),如果我們使用new,則這個新的變數將會被儲存在堆中。

並且在堆中儲存的資料我們可以根據需要手動的進行釋放,但是在棧中我們不能對其進行手動的釋放只能等待程式執行結束才會被自動釋放掉。

另外(Java) ;

堆(heap),在java 中用來給物件和JRE類分配記憶體,在任何時候我們建立的任何物件,它都會被分配到堆中。垃圾回收(Garbage Collection)會釋放掉這些物件當在程式中不存在它任何的索引(reference)。任何分配在堆中的物件都具有全域性的屬性。

棧(stack), 棧記憶體被用來執行一個執行緒。這些執行緒具有短存在性並且索引到堆中的物件。棧記憶體總是符合後進先出(Last-in-First-out)。

大體上,棧(stack)的記憶體遠小於對堆(heap)記憶體,而且棧(stack)的記憶體是固定大小的不能被增加。而堆(heap)的記憶體可以被作業系統增加。棧(stack)的速度更快。

程式功能介紹: 

void IninList() //對根結點進行初始化

void Push(int value) //將value接到連結串列的最後

int Pop() //將連結串列最後的一個元素pop出來

long long GetStackCount() //計算連結串列中共有多少元素

void PrintAll() //列印連結串列

typedef struct node{
 int val;
 struct node * next;
}*pNode;
pNode root;
pNode head;

void IninList()
{
root = (pNode)malloc(sizeof(node));   
roo->next = NULL;    
root->val = 0;
}
void Push(int value)

    	pNode newNode = NULL;    
	newNode = (struct node *) malloc(sizeof(* newNode));        
	head = root;//find the lastest one node.
		while(head->next)
		{
			head = head->next;   
		}
	newNode->next = NULL;
        newNode->val = value;
	head->next = newNode;
}

int Pop()
{
     //determine whether we pop all the node.
    if(!root->next)
    {
        printf("You Have Pop All The Element From The List.");
        return 0;
    }
    int temp;
    head = root;
    while(head->next->next)
    {
        head = head->next;
    }
   
    temp = head->next->val;
    head->next = NULL;
    return temp;
}
long long GetStackCount()
{
    head = root;
    long long num = 0;
    while(head->next)
    {
        head = head->next;
        num++;
    }
    return num;
}

void PrintAll()
{
    head = root;
    while(head->next)
    {
        printf("%d",head->next->val);
        printf("->");
        head = head->next;
    }
}
int main(int argc, const char * argv[]) {
    
    IninList();
    Push(1);
    Push(2);
    Push(3);
    Push(4);
    PrintAll();
    printf("The number of linked list is : %llu\n",GetStackCount());
    printf("first pop %d \n",Pop());
    printf("second pop %d \n",Pop());
    printf("third pop %d \n",Pop());
    printf("fourth pop %d \n",Pop());
    printf("fifth pop %d \n",Pop());

    printf("The number of linked list is : %llu\n",GetStackCount());
    PrintAll();
    
    return 0;
}