56 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第5天,点击查看活动详情


什么是栈

栈是一种特殊的线性结构,对数据增加及其删除只能在一端进行操作。 进行数据删除及增加的一端为栈顶,另一端为栈底。 增加数据为压栈。删除数据为出栈。 在这里插入图片描述

创建类型

typedef int StackTypeDate;

typedef struct stack
{
	StackTypeDate* arr;
	int top;
	int capacity;
}Stack;

初始栈

void InitStack(Stack* ps)
{
	assert(ps);
	ps->arr = NULL;
	ps->top = ps->capacity = 0;
}

压栈

压栈的时候要察看栈是不是满了,以及它为空的情况。

void StackPush(Stack* ps, StackTypeDate x)
{
	assert(ps);

	if (ps->capacity == ps->top)
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		ps->arr = (StackTypeDate*)realloc(ps->arr,sizeof(StackTypeDate) * newcapacity);
		ps->capacity = newcapacity;
	}

	ps->arr[ps->top] = x;
	ps->top++;
}

出栈

void StackPop(Stack* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	ps->top--;
}

察看栈顶的元素

StackTypeDate StackTop(Stack* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	//注意这里的减一
	return ps->arr[ps->top-1];
}

栈的个数

int StackSize(Stack* ps)
{
	assert(ps);

	return ps->top;
}

栈是否为空

bool StackEmpty(Stack* ps)
{
	assert(ps);

	return ps->capacity == 0;
}

栈的销毁

void StackDestroy(Stack* ps)
{
	assert(ps);
	free(ps->arr);
	ps->arr = NULL;
	ps->capacity = ps->top = 0;
}

复制带随机指针的链表

在这里插入图片描述

解题思路

1.原链表每个节点后面插入一个和它一样的节点。 新的链表就是插入的节点(还没有链接在一起) 在这里插入图片描述 2.复制节点中random指向的节点 == 原节点中random指向的节点的后一个节点。从上图中可以看出来。 3.恢复原链表,剪除新链表。 先让原链表中的节点指向新链表节点的下一个节点,原链表节点移动一位。 然后新链表中的节点指向原链表节点的下一个节点。一次遍历就行。

代码

struct Node* copyRandomList(struct Node* head) {
	struct Node* cur=head;
    while(cur)
    {
        struct Node *newnode=(struct Node*)malloc(sizeof(struct Node));
        newnode->val=cur->val;

        //插进去
        newnode->next=cur->next;
        cur->next=newnode;

        cur=newnode->next;
    }
    //random 指向恢复
    cur=head;
    while(cur)
    {
        struct Node* curnext=cur->next;
        if(cur->random==NULL)
        curnext->random=NULL;
        else
        curnext->random=cur->random->next;

        cur=curnext->next;
    }
    //恢复原链表,新成新链表
    cur=head;
    struct Node *newhead=NULL,*newtail=NULL;
    while(cur)
    {
        if(newtail==NULL)
        newhead=newtail=cur->next;
        cur->next=newtail->next;
        cur=cur->next;
        if(cur)
        newtail->next=cur->next;

        newtail=newtail->next;
    }
    return newhead;
}