反转链表
输入一个链表,反转链表后,输出链表的所有元素。
之前在LeetCode写过:
LeetCode:链表逆置
http://blog.csdn.net/bestzem/article/details/51873169
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode *pre=nullptr;
for(ListNode *cur=pHead;cur!=nullptr;){
ListNode *pNext=cur->next;
cur->next=pre;
pre=cur;
cur=pNext;
}
return pre;
}
};
合并两个排序的链表
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
之前在LeetCode写过:
LeetCode:Merge Two Sorted Lists
http://blog.csdn.net/bestzem/article/details/51882480
不过方法不一样,现在写的更简单。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
ListNode *pHead=new struct ListNode(0);
ListNode *cur=pHead,*cur1=pHead1,*cur2=pHead2;
for(;cur1!=nullptr&&cur2!=nullptr;cur=cur->next){
if(cur1->val<cur2->val){
cur->next=cur1;
cur1=cur1->next;
}
else{
cur->next=cur2;
cur2=cur2->next;
}
}
if(cur1){
cur->next=cur1;
}
if(cur2){
cur->next=cur2;
}
cur=pHead->next;
delete pHead;
return cur;
}
};