ListNode节点的定义
template<class T>
struct ListNode {
T val;
ListNode* next;
ListNode(T val) {
this->val = val;
this->next = nullptr;
}
};
链表的几个简单的题目
/*从文件中读取链表数据*/
template<class T>
ListNode<T>* readLinkedList(const char* fileName) {
ListNode<T>* list = new ListNode<T>(NULL);
ListNode<T>* dummyList = list;
T tempVal = NULL;
std::ifstream fin(fileName);
if (fin.is_open()) {
char tempChar;
while (fin >> tempChar && tempChar != ']') {
fin >> tempVal;
list->next = new ListNode<T>(tempVal);
list = list->next;
}
fin.close();
}
tempVal = NULL;
return dummyList->next;
}
/*合并两个非递减链表为非递增链表*/
// 合并到l1上
template<class T>
ListNode<T>* mergeTwoSortedList(ListNode<T>* l1, ListNode<T>* l2) {
if (l1 == nullptr) {
return reverseLinkedList(l2);
}
if (l2 == nullptr) {
return reverseLinkedList(l1);
}
if (l1 != nullptr && l2 != nullptr) {
ListNode<T>* p1 = l1;
ListNode<T>* p2 = l2;
// 使l1的头节点为最小值
if (l1->val > l2->val) {
p2 = l2->next;
l2->next = l1;
l1 = l2;
l2 = p2;
p1 = l1;
}
while (p1->next != nullptr && p2->next != nullptr) {
if (p1->val <= p2->val && p2->val <= p1->next->val) {
p2 = l2->next;
l2->next = p1->next;
p1->next = l2;
l2 = p2;
p1 = p1->next;
}
else {
p1 = p1->next;
}
}
while (p1->next != nullptr) {
p1 = p1->next;
}
if (p1->val <= p2->val) {
p1->next = p2;
}
}
return reverseLinkedList(l1);
}
/*链表逆序*/
template<class T>
ListNode<T>* reverseLinkedList(ListNode<T>* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
ListNode<T>* prev = head;
ListNode<T>* curr = head->next;
ListNode<T>* next = head;
while (curr != nullptr) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head->next = nullptr;
return prev;
}
/*顺序输出链表*/
template<class T>
void outputLinkedList(ListNode<T>* head, std::ofstream &fout) {
if (head != nullptr) {
fout << head->val << '\t';
outputnextedList(head->next, fout);
}
}
/*逆序输出链表*/
template<class T>
void reverseOutputLinkedList(ListNode<T>* head, std::ofstream &fout) {
if (head != nullptr) {
reverseOutputnextedList(head->next, fout);
fout << head->val << '\t';
}
}
转载:https://blog.csdn.net/CoderMaximum/article/details/101174386
查看评论