Data structures 交换链接列表的标题

Data structures 交换链接列表的标题,data-structures,linked-list,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->n

我从最近参加采访的朋友那里听到了这个问题:

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

例:

假定

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 {
    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;

谢谢虽然我不确定优化是什么意思。你说的优化是什么意思?这是在3个语句中完成的指针交换操作。谢谢!虽然我不确定优化是什么意思。你说的优化是什么意思?它是在3条语句中完成的指针交换操作。