一、合并两个有序链表
【题目】206. 反转链表
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { if(!head) return head; ListNode * curr = head->next; head->next = nullptr; while(curr) { ListNode *temp = curr->next; curr->next = head; head = curr; curr = temp; } return head; } };
二、合并两个有序链表
【题目】21. 合并两个有序链表
/** * * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(!l1 && !l2) return nullptr; else if(!l1) return l2; else if(!l2) return l1; ListNode node(), *head = &node; while(l1 && l2) { if(l1->val < l2->val) { head->next = l1; head = l1; l1 = l1->next; } else { head->next = l2; head = l2; l2 = l2->next; } } if(l1) head->next = l1; if(l2) head->next = l2; return node.next; } };
三、删除排序链表中的重复元素
【题目】83. 删除排序链表中的重复元素
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if(!head || !head->next) return head; ListNode *newhead = head; while(newhead->next) { if(newhead->val == newhead->next->val) { ListNode * p = newhead->next; newhead->next = newhead->next->next; delete(p); } else newhead = newhead->next; } return head; } };