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