C 資料結構 單鏈表

2022-06-12 04:06:09 字數 3540 閱讀 9804

這兩天看到很多有關單鏈表的面試題,對單鏈表都不知道是啥的我。經過學習和整理來分享一下啥是單鏈表和單鏈表的一些基本使用方法。最後看些網上有關單鏈表的面試題**例項。

單鏈表是一種鏈式訪問的資料結構,用一組位址任意的儲存單元存放線性表中的資料元素。這組儲存單元既可以是連續的,也可以是不連續的。

鍊錶的結點結構:

┌───┬───┐

│data│next│

└───┴───┘

data域--存放結點值的資料域[元素]

next域--存放結點的直接後繼的位址(位置)的指標域(鏈域)[指標]

用張圖來說明一下上面的定義:

在vs中看到單鏈表的結構如下圖:

單鍵表結點類-泛型

public class node          //資料域,當前結點資料

public class linklist //單鏈表頭

//構造

public linklist()

/// /// 增加新元素到單鏈表末尾

///

a = head;

while (a.next != null)

a.next = foot;}}

1.如果增加的是頭結點。直接把資料域(data)給head,next為空。因為只有乙個頭結點,沒有對應的下結點。

2.單鏈表是」不走回頭路「,所以每次增加都要從單鏈表的頭開始找到單鏈表最後乙個結點(最後乙個結點就是next為null),然後把最後乙個結點的next設定成需增加的結點,這時要需增加的結點變身為最後一結點,他的next為null。

public class linklist //單鏈表頭

//構造

public linklist()

public void delete(int i)

nodeb = new node();

b = head;

int j = 1;

while (b.next != null && j < i)

if (j == i)}}

1.如果刪除的是頭結點,那現在的頭結點就應該是頭結點的下一結點。

2.刪除結點如果不是頭結點。從單鏈表頭開始查詢要刪除結點的位置。並記錄刪除的前一結點值a和所要刪除的結點b。因為結點b被刪除了,所以結點a的next就應該為b的next。把結點a的next設定為結點b的next。

單鏈錶類 

public class linklist //單鏈表頭

//構造

public linklist()

/// /// 求單鏈表的長度

///

///

public int getlength()

return length;

}/// /// 判斷單鍵表是否為空

///

///

public bool isempty()

/// /// 清空單鏈表

///

public void clear()

/// /// 獲得當前位置單鏈表中結點的值

///

/// 結點位置

///

public t getnodevalue(int i)

nodea = new node();

a = head;

int j = 1;

while (a.next!=null && j/// 增加新元素到單鏈表末尾

///

a = head;

while (a.next != null)

a.next = foot;

}/// /// 增加單鏈表插入的位置

///

/// 結點內容

/// 結點插入的位置

public void insert(t item, int n)

if (n == 1) //增加到頭部

nodea = new node();

nodeb = new node();

b = head;

int j = 1;

while (b.next != null && j < n)

if (j==n)

}/// /// 刪除單鏈表結點

///

/// 刪除結點位置

///

public void delete(int i)

nodea = new node();

if (i == 1) //刪除頭

nodeb = new node();

b = head;

int j = 1;

while (b.next != null && j < i)

if (j == i)

}/// /// 顯示單鏈表

///

public void dispaly()

}#region 面試題

/// /// 單鏈表反轉

///

public void reverse()

nodenewnode = null;

nodecurrentnode = head;

nodetempnode = new node();

while (currentnode!=null)

head = newnode;

dispaly();

}/// /// 獲得單鏈表中間值

/// 思路:使用兩個指標,第乙個每次走一步,第二個每次走兩步:

///

public void getmiddlevalue()

if (b != null) //奇數

", a.data);

}else //偶數

和", a.data, a.next.data);}}

#endregion

}

呼叫例項

static void main(string args)

.第3:", link.getnodevalue(1), link.getnodevalue(3));

console.writeline("面試題-->單鏈表反轉");

link.reverse();

console.writeline("面試題-->獲得單鏈表中間值");

link.getmiddlevalue();

}

輸出結果:

C 資料結構 單鏈表

c 實現 首先,構造乙個單鏈表的節點類 class link 然後是以這個節點類為基礎,建立單鏈錶類 這裡簡單實現了單鏈表的兩個功能新增和輸出 class linklist if head.next null else if head.next null 列印全部資料 public void pri...

c 資料結構單鏈表

鍊錶定義 typedef struct linklistlinklist,linknode linklist 表示頭結點,linknode 表示節點linklist head linknode node 鍊錶初始化 bool linkinit linklist l l next null l dat...

C 資料結構 單鏈表

單鏈表的實現 include using namespace std template typename t struct node template typename t class linklist template typename t linklist linklist template t...