【经典算法】:链表翻转

比如说一个链表先是这样, 40 5 0 60 反过来就应该是 60 0 5 40

函数如下:


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;   //代表着最后一个
}

传进去的参数是链表头
原理就是把链表都反过来指,最后一个指向倒数第二个,方法是通过上述的三个数据结构完成的,next是为了遍历链表,而current和prev是为了表明指向的地点
注意的是:while循环里面第二三句绝对不能换

给出完整的程序:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
struct node{
    int data;
    struct node* next;
};
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;
}
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 printList(struct node *head)

    {

        struct node *temp = head;

        while(temp != NULL)

        {

            printf("%d  ", temp->data);

            temp = temp->next;

        }

    }
int main(){
    struct node* head = NULL;
    push(&head,20);
    push(&head,4);
    push(&head,15);
    push(&head,85);
    push(&head,60);
    push(&head,100);
    printList(head);
    reverse(&head);
    cout<<endl<<"翻转后的结果"<<endl;
    printList(head);
    return 0;
}

买一赠一,赠上求链表长度,链表长度函数

void find(struct node *head,int data){
    struct node *temp = head;
    while(temp!=NULL){
        if(temp->data==data){
            cout<<"已经找到了"<<endl;
            return ;
        }
        temp = temp->next;
    }
    cout<<"没有找到"<<endl;
}

int GetLength(struct node *head){
    int count = 0;
    struct node *temp = head;
    while(temp!=NULL){
        count++;
        temp = temp->next;
    }
    return count;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值