線性表 單鏈表 快慢指標

2022-05-08 13:09:06 字數 2038 閱讀 6709

快慢指標:

定義兩個指標,乙個快,乙個慢,可以有多種用途。例如:快速找到位置長度單鏈表中的中間結點;對於迴圈鍊錶中利用快慢指標也可以判斷是否存在環。

快速找到位置長度單鏈表中的中間結點

1)使用乙個指標,先索引一遍獲取總長度,再取長度一半去迴圈獲取到中間值;o(3l/2)。

2)使用兩個指標,快指標和慢指標,快指標一次向前走2格,慢指標一次走一格,當快指標走完全程,慢指標正好走在中間;

o(l/2)。

**實現:

//

快速查詢中間元素

int findmidele(linklist l, elemtype *e)

else

//是針對奇數個元素,再次進行操作,是之能夠退出

i++;

}*e = middle->data;

return

i;}

#include #include 

typedef

intelemtype;

typedef

intstatus;

typedef

struct

node node, *linklist;

//結點由存放資料的資料域和存放後繼結點位址的指標域組成

//單鏈表的插入

status listinsert(linklist* l, int i, elemtype e)//

l是指向頭節點的二級指標

int j=1

; linklist p = *l;

while (p && (j < i))//

找到要插入的位置

linklist n = (linklist)malloc(sizeof

(node));

n->data =e;

n->next = p->next;

p->next =n;

(*l)->data++; //

頭節點的資料域,表示當前鍊錶的長度

return1;

}//單鏈表的刪除

status listdelete(linklist* l, int i, elemtype*e)

linklist q = p->next; //

要刪除的結點

*e = q->data;

p->next = q->next;

free

(q);

(*l)->data--;

return1;

}void creatlisthead(linklist* l, intn)}

void creatlistend(linklist* l, intn)}

int findmidele(linklist l, elemtype*e)

else

i++;

}*e = middle->data;

returni;}

intmain()

linklist l;

creatlistend(&l, 10

); linklist p = l->next;

while

(p)

printf_s("\n

");intj,e;

printf_s(

"請輸入要刪除第幾個結點\n");

scanf_s("%d

",&j);

listdelete(&l, j, &e);

printf_s(

"刪除的結點為:%d\n

", e);

printf_s(

"刪除後的鍊錶為:\n");

p = l->next;

while

(p)

int i=findmidele(l,&e);

printf_s(

"中間元素為第%d結點%d\n

",i,e);

return1;

}

view code

線性表 單鏈表

define crt secure no deprecate define crt secure cpp overload standard names 1 includeusing namespace std typedef struct node node node headpointer 頭指...

線性表 單鏈表

單鏈表結構與順序儲存結構對比 一 儲存分配方式 1 順序儲存結構用一段連續的儲存單元依次儲存線性表的資料元素 2 單鏈表採用鏈式儲存結構,用一組任意的儲存單元存放線性表的元素 二 時間效能 1 查詢 順序儲存結構o 1 單鏈表o n 2 插入和刪除 順序儲存結構o n 單鏈表找到位置後插入刪除時間o...

線性表 單鏈表

template struct node template class linklist 無參建構函式,建立只有頭結點的空鍊錶 linklist t a int n 有參建構函式,建立有n個元素的單鏈表 linklist 析構函式 int length 求單鏈表的長度 t get int i 按位查...