单链表常见面试题(C语言实现)

总结常见的单链表操作函数,复习使用,仅供参考,代码调试通过。

#include<stdio.h>

typedef struct node{
    int data;
    struct node *next;
}node_t; 

//打印链表
void list_node(node_t *head){
    while(head){
        printf("%d",head->data);
        head=head->next;
    }
} 

//求链表长度
int list_len(node_t *head){
    int n=0;
    while(head)
    {
        ++n;
        head=head->next;
    }
    return n;
}

//反转链表
void reverse(node_t *head){
    node_t *r,*p,*q;
    r=NULL;
    p=head;
    q=p->next;
    while(p){
        p->next=r;
        r=p;
        p=q;
        if(q){
            q=q->next;
        }
    }
    head=r; 
} 

//测试函数
int main(){
    node_t d={4,0},c={3,&d},b={2,&c},a={1,&b};
    printf("%d
",list_len(&a));
    list_node(&a);
    reverse(&a);
    list_node(&d);
    return 0;
} 
 
原文地址:https://www.cnblogs.com/yinguojin/p/9833367.html