电脑故障

位置:IT落伍者 >> 电脑故障 >> 浏览文章

单链表交换任意两个元素(不包括表头)


发布日期:2019/12/5
 

先一次遍历找到这两个元素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;
}
注意特例如果相同元素就没有必要交换如果有一个是表头就不交换

上一篇:j初始值为0,j=j++;循环100遍值为多少?

下一篇:南京-乐天堂面试题