Given a linked list of numbers. Swap every 2 adjacent links
Given a linked list of numbers. Swap every 2 adjacent links. For example, if a linked list given to you is:
a->b->c->d->e->f
Output expected:
b->a->d->c->f->e
Every 2 alternate links have to be swapped.
I have written a solution here. Can you suggest me some other solution. Can you comment on my solution and help me better write it?
void SwapAdjacentNodes (Node head)
{
if (head == null) return;
if (head.next == null) return;
Node curr = head;
Node next = curr.Next;
Node temp = next.Next;
while (true)
{
temp = next.Next;
next.Next = curr;
curr.Next = temp;
if (curr.Next != null)
curr = curr.Next;
else
break;
if (curr.Next.Next!=null)
next = curr.Next.Next;
else
break;
}
}
Take a look at this C++ solution:
public void exchangeAdjElements(){
LLMain backup=current.next;
LLMain temp = current.next;
LLMain previous=current;
while(current!=null && current.next!=null){
previous.next=current.next;
current.next=temp.next;
temp.next=current;
if(current.next!=null){
previous=current;
current=current.next;
temp=current.next;
}
}
current=backup;
}
Here current is the head node.
Here's a rough sketch of a much simpler version, assuming Node has "Next" and "Data" members:
for (Node n = head; n && n.Next; n = n.Next.Next) {
void* tmp = n.Data;
n.Data = n.Next.Data;
n.Next.Data = tmp;
}
In other words, stop at every other node in the list and swap its data with the next one (the one). Simple.
Edit: Above solution swaps data within the nodes but not the nodes themselves. If you want to swap actual nodes, the solution requires more logic.
@dkamins: U are changing the values but in these type of questions, interviewers generally ask for pointer shuffling.
My attempt for the problem:
void swap (struct list **list1)
{
struct list *cur, *tmp, *next;
cur = *list1;
if(!cur || !cur->next)
return;
*list1 = cur->next;
while(cur && cur->next)
{
next = cur->next;
cur->next = next->next;
tmp = cur->next;
next->next = cur;
if(tmp && tmp->next)
cur->next = cur->next->next;
cur = tmp;
}
}
链接地址: http://www.djcxy.com/p/45922.html
上一篇: 在Ruby中不一致的隐式哈希创建?