Leetcode_206
反转链表
#include <iostream>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x): val(x),next(NULL) {}
};
ListNode* reverseList(ListNode* head)
{
ListNode *pre = NULL;
ListNode *cur = head;
while(cur!=NULL)
{
ListNode *next = cur->next;
cur ->next= pre ;
pre = cur;
cur = next;
}
return pre;
}
Leetcode_203
删除链表中指定的元素
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* removeElements(ListNode* head, int val)
{
ListNode* temp = new ListNode(0);
temp -> next = head;
ListNode *cur = temp;
while(cur!=NULL)
{
if(cur->next!=NULL&&cur->next->val==val)
{
ListNode *delnode = cur->next;
cur -> next = delnode->next;
delete delnode;
}
else
{
cur = cur->next;
}
}
ListNode *retNode = temp->next;
delete temp;
return retNode;
}
Leetcode_24
链表元素两两交换
#include <iostream>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x):val(x),next(NULL){}
};
ListNode* swapPairs(ListNode* head)
{
ListNode *temp = new ListNode(0);
temp->next = head;
ListNode *p = temp;
while(p->next && p->next->next)
{
ListNode *node1 = p->next;
ListNode *node2 = node1->next;
ListNode *next = node2->next;
node2->next = node1;
node1->next = next;
p->next = node2;
p = node1;
}
ListNode* retNode = temp->next;
return retNode;
}
Leetcode_237
删除指定节点
void deleteNode(ListNode* node) {
if(node==NULL)
return;
if(node->next == NULL)
delete node;
ListNode *delnode = node->next;
node->val = delnode -> val;
node ->next = delnode->next;
delete delnode;
}