c***2 发帖数: 838 | 1 Write a function for a linked list that exchanges the positions
of the nodes after the nodes referenced by two given pointers t and u.
(assume t and u are either in the list or NULL).
Example:
1 2 4 3 6 8 5 7 9 10
Exchange nodes after 2 and 3:
1 2 6 3 4 8 5 7 9 10
1) Don't do it by exchanging data.
2) Consider all possible cases. | t**d 发帖数: 352 | 2 what can be all all possible cases? all u,t, u,next() and t.next() have to
be not null, otherwise this function has no meaning.
so
if (t == null || u == null ) throw new NullPointerException();
if (t == u) return;
linkedList tnext = t.next();
linkedList unext = u.next();
if (tnext == null || unext == null ) throw new NullPointerException();
t._next = unext;
u._next = tnext;
linkedList temp = tnext.next();
tnext._next = unext.next();
unext._next = temp; | c***2 发帖数: 838 | 3 you are right and good. :-)
There is another valid case: one of them is NULL, the other is not.
In which case, move the non-null one to end of list. |
|