方法一:翻转链表
思路:
当右侧有更大值 就需要移除
翻转后 左侧有更大值 就需要移除
翻转后 8 3 13 2 5 定义一个最大值max == 第一个节点的值依次迭代
max = 8
max = 13
struct ListNode* reserve(struct ListNode* head )
{
struct ListNode* p1 = NULL;
struct ListNode* p2 = head;
struct ListNode* p3 = head->next;
while( p2 )
{
p2->next = p1;
p1 = p2;
p2 = p3;
if( p3 )p3 = p3->next;
}
return p1;
}
struct ListNode* removeNodes(struct ListNode* head)
{
struct ListNode* phead = reserve(head);
struct ListNode* prev = phead;
struct ListNode* temp = phead;
int max = prev->val;
phead = phead->next;
while( phead )
{
if( phead->val < max )
{
prev->next = phead->next;
phead = prev->next;
}
else
{
prev = phead;
max = phead->val;
phead = phead->next;
}
}
return reserve(temp);
}
方法二:递归法
struct ListNode *removeNodes(struct ListNode *head) {
if (head == NULL) {
return NULL;
}
head->next = removeNodes(head->next);
if (head->next != NULL && head->val < head->next->val) {
return head->next;
} else {
return head;
}
}
方法三:栈
int len(struct ListNode *head) {
int n = 0;
while (head != NULL) {
n++;
head = head->next;
}
return n;
}
struct ListNode *removeNodes(struct ListNode *head) {
struct ListNode **st = (struct ListNode **)malloc(sizeof(struct ListNode *) * len(head));
int top = -1;
for (; head != NULL; head = head->next) {
top++;
st[top] = head;
}
for (; top >= 0; top--) {
if (head == NULL || st[top]->val >= head->val) {
st[top]->next = head;
head = st[top];
}
}
return head;
}