重排链表(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宝啊

愿所有美好如期而遇

相关推荐
lyh13445 小时前
在macOS上运行Linux容器的方法
数据结构·状态模式
1白天的黑夜15 小时前
二叉树-226.翻转链表-力扣(LeetCode)
数据结构·c++·leetcode
编程绿豆侠6 小时前
力扣HOT100之贪心算法:45. 跳跃游戏 II
leetcode·游戏·贪心算法
黑听人6 小时前
【力扣 中等 C++】90. 子集 II
开发语言·数据结构·c++·算法·leetcode
黑听人7 小时前
【力扣 简单 C】21. 合并两个有序链表
c语言·开发语言·数据结构·算法·leetcode
ling__wx7 小时前
go部分语法记录
数据结构
黑听人7 小时前
【力扣 简单 C】83. 删除排序链表中的重复元素
c语言·开发语言·数据结构·算法·leetcode
编程绿豆侠8 小时前
力扣HOT100之技巧:75. 颜色分类
算法·leetcode·排序算法
Lenyiin9 小时前
第 87 场周赛:比较含退格的字符串、数组中的最长山脉、一手顺子、访问所有节点的最短路径
java·c++·python·leetcode·周赛·lenyiin
怀旧,9 小时前
【数据结构】7. 栈和队列
数据结构