一、头插法
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode* next) : val(x), next(next) {}
};
ListNode* InsertFromHead(ListNode* head,int x) {
ListNode* s = new ListNode(x);
s->next = head->next;
head->next = s;
return head->next;
}
int main() {
ListNode* head = new ListNode();
head->next = new ListNode(1);
head->next->next = new ListNode(2);
head->next->next->next = new ListNode(3);
ListNode *ans = InsertFromHead(head, 4);
ListNode* p = ans;
while (p) {
cout << p->val<<" ";
p = p->next;
}
return 0;
}
二、尾插法
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode* next) : val(x), next(next) {}
};
ListNode* InsertFromTail(ListNode* head, int x) {
ListNode* s = new ListNode(x);
s->next = NULL;
ListNode* tail = head;
while (tail->next) {
tail = tail->next;
}
tail->next = s;
tail = s;
return head->next;
}
int main() {
ListNode* head = new ListNode();
head->next = new ListNode(1);
head->next->next = new ListNode(2);
head->next->next->next = new ListNode(3);
ListNode *ans = InsertFromTail(head, 4);
ListNode* p = ans;
while (p) {
cout << p->val<<" ";
p = p->next;
}
return 0;
}