• 【数据结构】Reversing Linked List


    链表是否只对C/C++有意义?Java没有指针?
    答:链表是抽象的数据结构。一块存数据,一块存指针。

    问题:一个单链表,每k个元素逆序,返回头

    Sample Input:
    00100 6 4
    00000 4 99999
    00100 1 12309
    68237 6 -1
    33218 3 00000
    99999 5 68237
    12309 2 33218
    

    PAT是黑盒测试,取巧的方式是将原本链表的数据存在顺序表中,再逆序输出。如果让每k个逆序输出,那么可以使用堆栈,利用堆栈实现逆序输出。

    下面真正将链表逆序:
    首先直观地想,想象一串串起来的珠子,要逆序k个元素,就不断地将后面的往前放,放k个。然后用old,new,tmp三个指针来表达。

    #include <iostream>
    
    typedef struct LNode *List;
    struct  LNode{
        int Data;
        struct LNode *Next;
    };
    
    List CreatList(){
        List L;
        L=(List)malloc(sizeof(struct LNode));
        L->Data=0;
        L->Next=NULL;
        return L;
    };
    
    void Attach(List PtrL, int x,List *pRear){
        List tmpL;
        tmpL=(List)malloc(sizeof(struct LNode));
        
        tmpL->Data=x;
        tmpL->Next=NULL;
        
        (*pRear)->Next=tmpL;
        (*pRear)=tmpL;
    };
    
    void PrintList(List PtrL){
        List tmpL=PtrL->Next;
        
        while(tmpL){
            printf("%d",tmpL->Data);
            tmpL=tmpL->Next;
        }
    };
    
    List Reverse(List head, int k){
        List New,Old,tmpL;
        int cnt=1;
        
        New = head->Next;
        Old = New->Next;
        
        while(cnt<k){
            tmpL=Old->Next;
            Old->Next=New;
            New=Old;
            Old=tmpL;
            cnt++;
        }
        head->Next->Next=Old;
        head->Next=New;
        return head;
    };
    
    int main(int argc, const char * argv[]) {
        List L,Rear,RL;
        int x;
        
        Rear=L=CreatList();
        for(int i=0;i<5;i++){
            scanf("%d",&x);
            Attach(L, x,&Rear);
        }
        
        PrintList(L);
        printf("
    ");
        RL=Reverse(L, 4);
        PrintList(RL);
    
        return 0;
    }
    
  • 相关阅读:
    leetcode 416. Partition Equal Subset Sum
    leetcode 696. Count Binary Substrings
    leetcode 74. Search a 2D Matrix
    leetcode 199. Binary Tree Right Side View
    leetcode 43. Multiply Strings
    leetcode 695. Max Area of Island
    leetcode 257. Binary Tree Paths
    leetcode 694. Number of Distinct Islands
    ros使用时的注意事项&技巧2
    ros使用时的注意事项&技巧
  • 原文地址:https://www.cnblogs.com/maxwell-maxwill/p/12316179.html
Copyright © 2020-2023  润新知