交换链表的头部

SS *_*gde 0 linked-list data-structures

我最近参加面试的朋友听到了这个问题:

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

例如:

i/p: 1->2,3,4,5 (the given head is 1)
o/p: 2->1,3,4,5
Run Code Online (Sandbox Code Playgroud)

nne*_*neo 5

假设

struct node {
    struct node *next;
};
struct node *head;
Run Code Online (Sandbox Code Playgroud)

然后解决方案可能看起来像

struct node *next = head->next;
if(next == NULL) return head; // nothing to swap
head->next = next->next;
next->next = head;
head = next;
return next;
Run Code Online (Sandbox Code Playgroud)