1.leetcode203移除链表元素(简单)
题目连接:https://leetcode-cn.com/problems/remove-linked-list-elements/submissions/
解法:设置虚拟头节点
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* virtualhead = new ListNode();
virtualhead->next = head;
ListNode* p = virtualhead;
while (p->next != NULL)
{
if (p->next->val == val)
{
ListNode* tmp = p->next;
p->next = p->next->next;
delete tmp;
}
else
p = p->next;
}
head = virtualhead->next;
delete virtualhead;
return head;
}
};
注意:记得释放需要删除的节点的内存。
2.leetcode707设计链表(中等)
题目链接:https://leetcode-cn.com/problems/design-linked-list/
#include<iostream>
using namespace std;
class MyLinkedList {
public:
struct ListNode
{
int val;
ListNode* next;
ListNode(int val):val(val),next(NULL){}
};
ListNode* dummyHead;
MyLinkedList() {
dummyHead = new ListNode(0);
}
int get(int index) {
ListNode* p = dummyHead->next;
int i = 0;
while (p!= NULL && i < index)
{
p = p->next;
i++;
}
if (p!= NULL) return p->val;
else return -1;
}
void addAtHead(int val) {
ListNode* p = new ListNode(val);
ListNode* ret = dummyHead->next;
dummyHead->next = p;
p->next = ret;
}
void addAtTail(int val) {
ListNode* p = dummyHead;
while (p->next != NULL)
{
p = p->next;
}
ListNode* newNode = new ListNode(val);
p->next = newNode;
newNode->next = NULL;
}
void addAtIndex(int index, int val) {
if (index <= 0)
{
addAtHead(val);
return;
}
ListNode* p = dummyHead;
int i = 0;
while (p!= NULL && i < index)
{
p = p->next;
i++;
}
if (p!= NULL)
{
ListNode *newnode=new ListNode(val);
newnode->next = p->next;
p->next = newnode;
}
}
void deleteAtIndex(int index) {
if(index == 0)
{
ListNode* p = dummyHead->next;
dummyHead->next = p->next;
delete p;
return;
}
else if (index > 0)
{
ListNode* p = dummyHead;
int i = 0;
while (p!= NULL && i < index)
{
p = p->next;
i++;
}
if(p == NULL)
{
return;
}
else if(p->next != NULL)
{
ListNode* ret = p->next;
p->next = ret->next;
delete ret;
return;
}
}
}
};
3.leetcode206反转链表(简单)
题目链接:https://leetcode-cn.com/problems/reverse-linked-list/
#include<iostream>
using namespace std;
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) return head;
else
{
ListNode* newhead = NULL;
while (head != NULL)
{
ListNode* tmp = head->next;
head->next = newhead;
newhead = head;
head = tmp;
}
return newhead;
}
}
};
4.leetcode24两两交换链表中的节点(中等)
题目链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/submissions/
解法一、递归法
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == NULL || head->next == NULL)
{
return head;
}
else
{
ListNode* newhead = head->next;
head->next = swapPairs(newhead->next);
newhead->next = head;
return newhead;
}
}
};
解法二 非递归法
|