美文网首页工作生活
链表逆置C语言完整代码

链表逆置C语言完整代码

作者: zhake | 来源:发表于2019-07-02 20:22 被阅读0次

    链表逆置C语言完整代码

    #include<stdio.h>
    
    typedef struct node {
        int num;
        struct node *next;
    }Lnode;
    
    
    
    Lnode *createlink(int n)
    {
        int num;
        Lnode *head = NULL;
        Lnode *pend = head;
        
        while (n > 0)
        {
            scanf("%d", &num);
            Lnode *pnew = (struct node*)malloc(sizeof(struct node));
            pnew->num = num;
            pnew->next = NULL; //新创建的指针的下一个位置还没有定
            if (head == NULL)
            {
                head = pnew;
                pend = pnew;
            }
            else
            {
                pend->next = pnew;
                pend = pnew;
            }
            n--;
        }
        
        return head;
    }
    
    
    int isPalindrome(Lnode* head) {//O(n)、O(1)
        Lnode* slow = head, *fast = head, *prev = NULL;
        while (fast) {//find mid node
            slow = slow->next;
            fast = fast->next ? fast->next->next : fast->next;
        }
        while (slow) {//reverse
            Lnode* ovn = slow->next;
            slow->next = prev;
            prev = slow;
            slow = ovn;
        }
        while (head && prev) {//check
            if (head->num != prev->num) {
                return 0;
            }
            head = head->next;
            prev = prev->next;
        }
        return 1;
    }
    
    
    void print(Lnode* L) {
        Lnode* p = L;
        while (p)
        {
            printf("%d", p->num);
            p = p->next;
        }
        printf("\n");
    }
    
    int main() {
        Lnode *L;
        L = createlink(5);
        print(L);
        printf("\n");
        printf("真假%d\n", isPalindrome(L));
        
        
        print(L);
    }
    

    相关文章

      网友评论

        本文标题:链表逆置C语言完整代码

        本文链接:https://www.haomeiwen.com/subject/pizthctx.html