【问题标题】:Swap the head of the linked list交换链表的头部
【发布时间】: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


    【解决方案1】:

    假设

    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 个语句中完成的指针交换操作。
    【解决方案2】:
    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
    

    【讨论】:

      猜你喜欢
      • 2019-01-28
      • 1970-01-01
      • 2020-06-23
      • 2021-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      相关资源
      最近更新 更多