實現鍊錶及相關的方法 2

2021-10-09 18:47:23 字數 2602 閱讀 5006

思路:

下面提供兩種方法,其實大同小異,但是因為鍊錶的最後乙個元素需要指向空,如果少了這個就會出現問題。所以在方法二中,遍歷的過程就將末尾指向空。

方法一:

//將大的資料放在x的右邊,小的資料放在x的左邊

public listnode parttition

(int x)

else

}else

else

} cur = cur.next;

}//小部分的頭要是為空,則返回大部分的頭

if(beforestart == null)

//將兩部分串起來

beforeend.next = afterstart;

if(afterstart != null)

//大部分不等於空的時候,將大部分最後節點的next指向空

return beforestart;

}

方法二:

//將大的資料放在x的右邊,小的資料放在x的左邊

//改進版

public listnode parttition2

(int x)

else

}else

else

}//cur = cur.next;

cur = curnext;

}//小部分的頭要是為空,則返回大部分的頭

if(beforestart == null)

//將兩部分串起來

beforeend.next = afterstart;

return beforestart;

}

//刪除重複的節點

public listnode deleteduplication()

//退出迴圈需要多走一步

cur = cur.next;

//the first way

tmp.next=cur;

}else

}//the second way

// tmp.next = null;

return node.next;

}

思路:使用快慢指標,將後邊鍊錶進行反轉,然後兩段進行迴圈對比判斷是否為回文。

//判斷回文

public

boolean

chkpalindrome()

listnode p=slow.next;

//將後半鍊錶指向反轉

while

(p!=null)

//judge palindrome

listnode phead=

this

.head;

while

(phead!=slow)

//偶數

if(phead.next==slow)

phead=phead.next;

slow=slow.next;

}return

true

;}

思路:見部落格:

//在鍊錶中建立乙個環

public

void

createloop()

system.out.

println

("3");

cur.next=

this

.head.next;

}//判斷這個鍊錶中是否有環

public

boolean

hascycle1()

}return

false

;}

public listnode detectcycle()

}//沒有環則返回null

if(fast==null || slow==null)

// 讓其中乙個引用處於頭的位置,另乙個引用不動,兩個引用分別一人一步走

slow=

this

.head;

while

(slow!=fast)

return slow;

}

思路見部落格: 環形鍊錶 iii (求鍊錶中環的長度).

//求鍊錶中環的長度

public

intcyclelistlength()

}//沒有環則返回null

if(fast==null || fast.next==null)

// 讓其中乙個引用處於頭的位置,另乙個引用不動,其中乙個引用一步一步向後走,用count計數,直到兩個引用相遇

slow=

this

.head;

int count=1;

slow=slow.next;

//讓slow先走一步

while

(slow!=fast)

return count;

}

實現鍊錶及相關的方法 1

本篇部落格主要是自己實現一下鍊錶。節點類 class listnode 該鍊錶為不帶頭結點的單鏈表,並且裡邊有很多鍊錶基本操作的例項方法,下面一一介紹。public class mysignallist public void addfirst int data else 尾插法 也要分是否為第一次...

鍊錶的相關實現

class node public class lianbiao else head node size 頭刪 public void popfront head head.next if head null else size 尾插 void pushback int val else size ...

linux 鍊錶及相關鍊錶操作

1.鍊錶結構體 struct list head2.list entry define container of ptr,type,member container of ptr,type,member ptr為list head指標,type為包含list head結構體物件型別,member為鍊...