链表<总结一>

来源:互联网 发布:数据库怎么导入excel 编辑:程序博客网 时间:2024/06/05 15:42
 

    链表的基本知识点:

    单链表逆置

    判断链表是否有环

    从无头单链表中删除节点

    判断两个单链表是否相交

     

    从无头单链表中删除节点

    假设有一个没有头指针的单链表。一个指针指向此单链表中间的一个节点(不是第一个,也不是最后一个),请将该节点从单链表中删除。

    解答:将该指针指向的节点的后一个节点的值,赋给该节点,之后删除后一个节点。

     

    编程判断两个链表是否相交

    给出两个单向链表的头指针,分别为h1和h2,判断两个单链表是否相交(两单链表均不带环)

    解法一:

    从h1开始,遍历第一个链表,直到第一个链表的尾节点x,记录下来。

    从h2开始,遍历第二个链表,看是否能遍历到尾节点x。

     

    解法二:

             从h1开始,遍历第一个链表,直到第一个链表的尾节点x,将x的next指针指向h2。

    从h2开始,遍历第二个链表,如果能回到h2,即两个单链表相交。

     

    解法三:计算链表长度x1,x2,对地址hash计数y,计算y和x1+x2的关系

     

    具体实现:

    #include<stdio.h>

    #include<stdlib.h>

     

    struct node{

           int data;

           struct node * next;

    };

     

    //链表逆转

    struct node * reverse(struct node* head){

           if(NULL == head){

                   printf("head is null err");

                   return NULL;

           }

           struct node * p1 = head;

           struct node * p2 = p1->next;

           struct node * p3;

          

           while(p1 && p2){

                    p3 = p2->next;

                    p2->next = p1;

                    p1 = p2;

                    p2 = p3;

           }

           head->next = NULL;

           return p1;

    }

     

    //判断是否是循环链表

    bool isLoop(struct node *head){

         struct node * p = head;

         struct node * q = head;

         while(q && q->next){

                 p = p->next;

                 q = q->next->next;

                 if(p == q){

                      return 1;

                 }

         }

         return 0;

    }

     

    int main(){

       

        struct node * head = NULL;

        head = (struct node *)malloc(sizeof(struct node));

        if(NULL == head){

                printf("memory allocation error");

        }

        head->data = 1;

        head->next = NULL;

       

        struct node * p;

        struct node * q = head;

        int i=0,num,input;

       

        scanf("%d",&num);

        while(i<num){

            scanf("%d",&input);

            p = (struct node *)malloc(sizeof(struct node));

            if(NULL == p){

                printf("memory allocation error");

            }

            p->data = input;

            p->next = NULL;

            q->next = p;

            q = p;

            i++;

        }

       

        //构造循环链表测试

        //q->next = head;

        //printf("%d\n",isLoop(head));

       

        struct node* new_head = reverse(head->next);

       

        if(new_head){

             q = new_head;

             while(NULL != q){

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

                 q = q->next;

             }

        }else{

              printf("reverse err");

        }

        system("pause");

        return 0;

    }

     

     

原创粉丝点击