交换链表的头部

时间:2012-10-11 04:29:59

标签: data-structures linked-list

我最近刚接受采访的朋友听到了这个问题:

给定链表的头部,编写一个函数将头部与链表中的下一个元素交换,并将指针返回到新的头部。

例如:

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

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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