zoukankan      html  css  js  c++  java
  • 反转单链表

    单链表逆置,超级热门的面试题,感觉最近见的比较多啊

    一种方法是非递归,一种方法是递归

    非递归方法:

    #include <iostream>
    #include<cstdio>
    #include<cstdlib>
    using namespace std;
    
    /*链表结构体*/
    struct Node{
        int data;
        struct Node* next;
    };
    static void reverse(struct Node** head_ref){                 //函数形参采用双指针,即指针的指针,至于为什么要用双指针,可以看主函数的调用情况
      /*建立三个结构体指针*/
    struct Node* prev =NULL; struct Node* current =*head_ref; struct Node* next; while(current!=NULL){ next =current->next; current->next=prev; prev=current; current=next; } *head_ref=prev; }
    /*头插法增加节点*/
    void push(struct Node** head_ref,int new_data){ struct Node* new_node= (struct Node*)malloc(sizeof(struct Node)); new_node->data=new_data; new_node->next=(*head_ref); (*head_ref)=new_node; }
    /*打印节点*/
    void printList(struct Node *head){ struct Node *temp=head; while(temp!=NULL){ cout<<temp->data<<" "; temp=temp->next; } }
    int main() { struct Node *head=NULL; push(&head,2); push(&head,4); push(&head,6); push(&head,8); printList(head); reverse(&head); cout<<endl; printList(head); return 0; }
  • 相关阅读:
    汇编-实验9
    Starling开源手势库AcheGesture
    Robotlegs2的Starling扩展
    Flash Builder 4.6/4.7 注释以及字体大小修改
    js中函数的理解
    js对象引用赋值后
    var声明提前 undefined
    光棍节程序员闯关秀
    body和普通div背景图宽高百分比的区别
    笔试题
  • 原文地址:https://www.cnblogs.com/umrx/p/7476511.html
Copyright © 2011-2022 走看看