[蓝蓝计算机考研算法训练二期]-day14

85 阅读2分钟

19、删除排序链表中的重复元素

给定一个已排序的链表的头 head删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表

示例 1:

输入:head = [1,1,2] 输出:[1,2]

示例 2:

输入:head = [1,1,2,3,3] 输出:[1,2,3]

提示:

  • 链表中节点数目在范围 [0, 300] 内

  • -100 <= Node.val <= 100

  • 题目数据保证链表已经按升序 排列

代码:

#include <stdio.h>
#include <stdlib.h>
//链表结构体
struct LNode{
    int val;
    struct LNode *next;
};
//创建链表
struct LNode *createList(){
    int val;
    printf("shuru\n");
    scanf("%d",&val);
    struct LNode*head=NULL;
    struct LNode*current=NULL;
    while(val!=-1){
        struct LNode *node=(struct LNode*) malloc(sizeof (struct LNode));
        node->val=val;
        node->next=NULL;
        if(head==NULL){
            head=node;
            current=node;
        }else{
            current->next=node;
            current=node;
        }
        scanf("%d", &val);
    }
    return head;

}
//删除排序链表中的元素
struct LNode *deletelist(struct LNode*head){
    struct LNode* current=head;
    while(current!=NULL&&current->next!=NULL){
        if(current->val==current->next->val){
            struct LNode *temp=current->next;
            current->next=temp->next;
            free(temp);
        }else{
            current=current->next;
        }

    }
    return head;
}

//打印
void printlist(struct LNode*head){
    struct LNode*current=head;
    while(current!=NULL){
        printf("%d ",current->val);
        current=current->next;
    }
}


int main(){
    struct LNode *list=createList();//创建链表返回的结构体类型的头节点
    struct LNode *result=deletelist(list);
    printlist(result);

    return 0;


}

20、反转链表

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

示例 1:

输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1] 示例 2:

输入:head = [1,2] 输出:[2,1] 示例 3:

输入:head = [] 输出:[]

提示:

  • 链表中节点的数目范围是 [0, 5000]
  • -5000 <= Node.val <= 5000
#include <stdio.h>
#include <stdlib.h>
struct LNode{
    int val;
    struct LNode*next;
};
//创建链表
struct LNode* createlist(){
    int val=0;
    printf("shuruzhi\n");
    scanf("%d",&val);
    struct LNode*cur=NULL;
    struct LNode*head=NULL;
    while(val!=-1){
        struct LNode* node=(struct LNode*) malloc(sizeof (struct LNode));
        node->val=val;
        node->next=NULL;
        if(head==NULL){
            head=node;
            cur=node;
        }else{
            cur->next=node;
            cur=node;
        }
        scanf("%d",&val);
    }
    return head;
}





struct LNode* fanzhuanlist(struct LNode*head){

    struct LNode*L= malloc(sizeof (struct LNode*));
    L->next=head;
    struct LNode *p,*q;
    p=L->next;
    L->next=NULL;
    while(p!=NULL){
        q=p->next;
        p->next=L->next;
        L->next=p;
        p=q;
    }
    struct LNode *pre=L->next;
    return pre;
}





void printlist(struct LNode*head){
    struct LNode *P=head;
    while(P!=NULL){
        printf("%d ",P->val);
        P=P->next;
    }
}

int main() {
    struct LNode *list=createlist();//创建链表
    struct LNode *fan=fanzhuanlist(list);  //删除链表
    printlist(fan);
    return 0;
}