反轉鏈表
題目描述
輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == NULL || pHead->next == NULL) return pHead;
ListNode *p = NULL;
for(p;pHead;swap(p,pHead))
{
swap(pHead->next,p);
}
return p;
}
};
合併兩個排序的鏈表
題目描述
輸入兩個單調遞增的鏈表,輸出兩個鏈表合成後的鏈表,當然我們需要合成後的鏈表滿足單調不減規則。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
auto dummy = new ListNode(-1);//定義一個虛擬表頭
auto cur = dummy;//定義一個移動節點
while(pHead1 && pHead2)//遍歷
{
if(pHead1->val < pHead2->val)//小的數在前面
{
cur->next = pHead1;
pHead1 = pHead1->next;
}
else
{
cur->next = pHead2;
pHead2 = pHead2->next;
}
cur = cur->next;
}
if(pHead1)cur->next = pHead1;//最後總會多一個數,無法進行比較
else cur->next = pHead2;//所以多了的那個數直接插入到最後
return dummy->next;
}
};