熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> 數據結構 >> 正文

單鏈表交換任意兩個元素(不包括表頭)

2022-06-13   來源: 數據結構 

先一次遍歷找到這兩個元素curr和curr同時存儲這兩個元素的前驅元素pre和pre
然後大換血
public static Link SwitchPoints(Link head Link p Link q)
{
if (p == head || q == head)
throw new Exception(&#;No exchange with head&#;);
if (p == q)
return head;
//find p and q in the link
Link curr = head;
Link curr = p;
Link curr = q;
Link pre = null;
Link pre = null;

int count = ;
while (curr != null)
{
if (currNext == p)
{
pre = curr;
count++;
if (count == )
break;
}
else if (currNext == q)
{
pre = curr;
count++;
if (count == )
break;
}
curr = currNext;
}
curr = currNext;
preNext = curr;
currNext = currNext;
preNext = curr;
currNext = curr;
return head;
}
注意特例如果相同元素就沒有必要交換如果有一個是表頭就不交換


From:http://tw.wingwit.com/Article/program/sjjg/201404/30588.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.