重排链表(C语言)



题目:

示例:


思路:

这题我们将使用栈解决这个问题,利用栈先进后出的特点,从链表的中间位置进行入栈,寻找链表的中间位置参考:删除链表的中间节点,之后从头开始进行连接。

本题使用的栈源代码在此处:栈和队列的实现

图示:


代码:

复制代码
//栈
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>

typedef struct ListNode* DataType;
typedef struct Stack
{
	DataType* data;
	int top;
	int capacity;
}Stack;
 
void Init(Stack *st);
void Push(Stack* st, DataType x);
void Pop(Stack* st);
DataType GetTop(Stack* st);
bool Empty(Stack* st);

void Init(Stack* st)
{
	assert(st);
 
	st->data = NULL;
	st->top = 0;
	st->capacity = 0;
}
 
void Push(Stack* st, DataType x)
{
	assert(st);
 
	if (st->capacity == st->top)
	{
		int newcapacity = (st->capacity == 0) ? 4 : st->capacity * 2;
 
		DataType* temp = (DataType*)realloc(st->data, sizeof(DataType) * newcapacity);
		if (temp == NULL)
		{
			perror("realloc fail");
			exit(-1);
		}
 
		st->data = temp;
		st->capacity = newcapacity;
	}
 
	st->data[st->top++] = x;
}
 
void Pop(Stack* st)
{
	assert(st);
	assert(st->top > 0);
 
	st->top--;
}
 
DataType GetTop(Stack* st)
{
	assert(st);
	assert(st->top > 0);
 
	return st->data[st->top - 1];
}
 
bool Empty(Stack* st)
{
	assert(st);
 
	return (st->top == 0);
}
 
//寻找链表的中间位置
struct ListNode* findMiddle(struct ListNode* head)
{
    if(head == NULL || head->next == NULL)
        return NULL;
 
    struct ListNode* slow = head;
    struct ListNode* fast = head;
 
    while(fast && fast->next)
    {
        slow = slow->next;
        fast = fast->next->next;
    }
 
    return slow;
}

//于此处开始正式解题
void reorderList(struct ListNode* head)
{
    if(head == NULL || head->next == NULL)
        return head;

    Stack list;
    Init(&list);

    struct ListNode* middle = findMiddle(head);
    while(middle)
    {
        Push(&list,middle);
        middle = middle->next;
    }
    
    struct ListNode* cur = head;
    struct ListNode* next = NULL;

    int flag = 1;
    while(!Empty(&list))
    {
       
        if(flag == 1)
        {
            next = cur->next;

            cur->next = GetTop(&list);
            Pop(&list);

            flag = 0;
        }
        else
        {
            cur->next = next;
            flag = 1;
        }
        cur = cur->next;
       
    }
    cur->next = NULL;

    return head;
}

个人主页:Lei宝啊

愿所有美好如期而遇

相关推荐
我爱996!10 小时前
LinkedList与链表
数据结构·链表
yb0os110 小时前
RPC实战和核心原理学习(一)----基础
java·开发语言·网络·数据结构·学习·计算机·rpc
hope_wisdom11 小时前
C/C++数据结构之栈基础
c语言·数据结构·c++··stack
Lris-KK11 小时前
【Leetcode】高频SQL基础题--1341.电影评分
sql·leetcode
B612 little star king12 小时前
力扣29. 两数相除题解
java·算法·leetcode
野犬寒鸦12 小时前
力扣hot100:环形链表(快慢指针法)(141)
java·数据结构·算法·leetcode·面试·职场和发展
Miraitowa_cheems12 小时前
LeetCode算法日记 - Day 38: 二叉树的锯齿形层序遍历、二叉树最大宽度
java·linux·运维·算法·leetcode·链表·职场和发展
宁檬精14 小时前
算法练习——55.跳跃游戏
数据结构·算法·游戏
XFF不秃头14 小时前
力扣刷题笔记-三数之和
c++·笔记·算法·leetcode
高山有多高16 小时前
顺序表:数据结构中的基础线性存储结构
数据结构