鍊錶相關操作

2021-07-29 02:57:53 字數 1796 閱讀 7337

class listnode

}

1.鍊錶反轉,遍歷原鍊錶,採用頭插法將數值插入新鍊錶

public listnode reverse(listnode p)

return cur;

}

2.兩個鍊錶相加,如:1->2->3加4->5->6等於5->7->9。思路:短的鍊錶高位用0補。

public class solution 

int sum = 0, carry = 0;

listnode curr = dummyhead;

while(l1!=null || l2!=null)

if(carry!=0)

return dummyhead.next;

}}

3.尋找單鏈表的環點,定義乙個快速指標和慢速指標,當快速指標與慢速指標相遇時,鍊錶存在環,當快速指標遇到null時,鍊錶無環。

public boolean i***istloop(listnode p)

return fast!=null&&fast.next!=null;

}

4.尋找單鏈錶環點的位置,定理:

碰撞點p到連線點的距離=頭指標到連線點的距離,因此,分別從碰撞點、頭指標開始走,相遇的那個點就是連線點。

public listnode looplocation(listnode p)

if(fast!=null&&fast.next!=null)

return slow;

}return null;

}

5.

環的長度,在碰撞點處,快指標與慢指標繼續走,繼續相遇的運算元即為換的長度。

6.鍊錶的長度,換的長度加上頭指標到環點位置的長度即為單鏈表的長度。

7.判斷兩個鍊錶相交,如果兩個鍊錶相交,則他們最後乙個元素一定相同。

public boolean isconnloop(listnode h1, listnode h2)

8.兩個鍊錶相交的位置:

public listnode findpointnloop(listnode h1, listnode h2)   

while (n2 != null)

n1 = h1;

n2 = h2;

if (len1 < len2)

for (int i = len1-len2; i > 0; i--)

n1 = n1.next;

while (n1 != null && n1 != n2)

return n1;

}

9.

如果鍊錶有環且相交,那麼這兩個鍊錶都是有環的。

找到第乙個鍊錶的環點,然後將環斷開(當然不要忘記了儲存它的下乙個節點),然後再來遍歷第二個鍊錶,如果發現第二個鍊錶從有環變成了無環,那麼他們就是相交的嘛,否則就是不相交的了。

public boolean isconloop(listnode h1, listnode h2)  else   

}

public listnode loopentry(listnode head)

if (fast == slow)

return slow;

} return null;

}

鍊錶相關操作

include include using namespace std 鍊錶結構體 struct listnode 是否為空 bool isempty listnode list position是否是最後乙個 bool islast listnode position,listnode list ...

鍊錶相關操作

關於鍊錶的頭插法 尾插法 刪除節點 插入節點。include include typedef struct listlist,linklist linklist creat onhead linklist head,int x linklist creat ontail linklist head,...

java實現鍊錶相關操作

public class test 構造乙個鍊錶 return 煉表頭結點 private static node createlink int count else return node 輸出鍊錶 param head 煉表頭結點 private static void printnodelin...