一、链表翻转(leetcode206)
就地逆置法
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* next = NULL;
ListNode* temp = NULL;
while(head)
{
next = head->next;
head->next = temp;
temp = head;
head = next;
}
return temp;
}
};
头插法
#include <iostream>
using namespace std;
struct listnode
{
int value;
listnode *next;
listnode( int x): value(x), next(NULL) {}
};
int main()
{
listnode a(10);
listnode b(20);
listnode c(30);
listnode d(40);
listnode e(50);
a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;
listnode *head = &a;
listnode new_node(0);
listnode *next = NULL;
while(head)
{
next = head->next;
head->next = new_node.next;
new_node.next = head;
head = next;
}
listnode *new_head = new_node.next;
while(new_head)
{
cout<<new_head->value<<" ";
new_head = new_head->next;
}
cout<<endl;
return 0;
}
这两种方法其实没什么差别
二、链表中间段逆序(leetcodde92)
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
int len = n - m + 1;
ListNode* pre_node = NULL;
ListNode* pnode = head;
while(head && --m)
{
pre_node = head;
head = head->next;
}
ListNode* list_tail = head;
ListNode* new_head = NULL;
ListNode* next = NULL;
while(head && len--)
{
next = head->next;
head->next = new_head;
new_head = head;
head = next;
}
list_tail->next = head;
if(pre_node)
{
pre_node->next = new_head;
return pnode;
}
else
return new_head;
}
};
三、求公共节点(leetcode160)
//方法一
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
std::set<ListNode*> node_set;
while(headA)
{
node_set.insert(headA);
headA = headA->next;
}
while(headB)
{
if(node_set.find(headB) != node_set.end())
return headB;
headB = headB->next;
}
return NULL;
}
};
//方法二
int get_len(ListNode* head)
{
int len = 0;
while(head)
{
len++;
head = head->next;
}
return len;
}
ListNode* forward( int blen, int slen, ListNode* head)
{
int len = blen - slen;
while(head && len)
{
head = head->next;
len--;
}
return head;
}
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int lenA = get_len(headA);
int lenB = get_len(headB);
if( lenA > lenB)
{
headA = forward(lenA, lenB, headA);
}
else
{
headB = forward(lenB, lenA, headB);
}
while(headB && headA)
{
if(headB == headA)
{
return headB;
}
headA = headA->next;
headB = headB->next;
}
return NULL;
}
};
四、合并有序链表(leetcode21)
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode temp_node(0);
ListNode* pre;
pre = &temp_node;
while(l1 && l2)
{
if(l1->val < l2->val)
{
pre->next = l1;
l1 = l1->next;
}
else
{
pre->next = l2;
l2 = l2->next;
}
pre = pre->next;
}
if(l1)
pre->next = l1;
if(l2)
pre->next = l2;
return temp_node.next;
}
};