2012-10-11 74 views
0

我听说我的朋友谁参加了最近一次采访中这个问题的头:鉴于链表的头交换链表

,写一个函数,在链接的下一个元素换头列出并返回指向新头的指针。

例:

i/p: 1->2,3,4,5 (the given head is 1) 
o/p: 2->1,3,4,5 

回答

5

假设

struct node { 
    struct node *next; 
}; 
struct node *head; 

那么解决办法可能看起来像

struct node *next = head->next; 
if(next == NULL) return head; // nothing to swap 
head->next = next->next; 
next->next = head; 
head = next; 
return next; 
+0

谢谢!虽然我不确定优化。 –

+0

这里的优化是什么意思?这是在3个语句中完成的指针交换操作。 – fayyazkl

1
struct node* head; 

struct node *tmp1,*tmp2; 
tmp1=head; // save first node pointer 
tmp2=head->next->next; // save third node pointer 
head=head->next; // Move Head to the second node 
head->next=tmp1; // swap 
head->next->next=tmp2; // Restore the link to third node