【发布时间】:2012-10-11 04:29:59
【问题描述】:
我从最近参加面试的朋友那里听到了这个问题:
给定链表的头,编写一个函数,将头与链表中的下一个元素交换,并返回指向新头的指针。
例如:
i/p: 1->2,3,4,5 (the given head is 1)
o/p: 2->1,3,4,5
【问题讨论】:
标签: data-structures linked-list
我从最近参加面试的朋友那里听到了这个问题:
给定链表的头,编写一个函数,将头与链表中的下一个元素交换,并返回指向新头的指针。
例如:
i/p: 1->2,3,4,5 (the given head is 1)
o/p: 2->1,3,4,5
【问题讨论】:
标签: data-structures linked-list
假设
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;
【讨论】:
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
【讨论】: