取next之前判断指针非空,取next之前判断指针非空,取next之前判断指针非空,重要的事情说三遍。
下面说题目,第一题思路就是在保持内存的情况下替换对应值即可,比较容易;第二题思路则是拿两个指针来记录小的部分和大的部分,然后连起来。注意链表尾节点的next定义为NULL。
另:第二题在思路不变的情况下,可以缩减代码长度。对于未定义指针可以先赋一个结构体,来避免NULL的尴尬。可以适当增加变量数量,避免变量重复使用而增加的代码量。
第一题:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class Remove {
public:
// 把当前节点的值由next代替,并指向next后面那个节点
bool removeNode(ListNode* pNode) {
// write code here
if (!pNode)
return true; // 取决于尾节点的定义
else
{
ListNode* temp = pNode->next;
if (!temp)
return false;
else
{
pNode->val = temp->val;
pNode->next = temp->next;
return true;
}
}
}
};
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class Partition {
public:
// 题目理解为比较节点的value来决定在哪一块,但是每一块内部顺序不变
// 两个指针,最后合并
ListNode* partition(ListNode* pHead, int x) {
// write code here
if (!pHead)
return NULL;
else
{
ListNode *low, *high, *temp, *last;
low = high = last = NULL;
temp = pHead;
if (pHead->val < x)
low = pHead;
else
{
high = pHead;
last = high;
}
temp = pHead->next;
while(temp)
{
if (temp->val < x)
{
if (!low)
{
low = temp;
pHead = low;
}
else
{
low->next = temp;
low = temp;
}
}
else
{
if (!high)
{
high = temp;
last = high;
}
else
{
high->next = temp;
high =temp;
}
}
temp = temp->next;
}
if(low)
low->next = last;
if (high)
high->next = NULL;
return pHead;
}
}
};