一、链表
class
InsertValue {
public :
2、对于一个链表,我们需要用一个特定阈值完成对它的分化,使得小于等于这个值的结点移到前面,大于该值的结点在后面,同时保证两类结点内部的位置关系不变。
public
:
1、在节点值有序的单循环链表中插入指定结点,使插入后的链表依然有序。
解法:一下解法只是单链表,不是循环链表。
public :
ListNode* buildLinkedList(vector<
int
> &A,vector<
int
> &nextPoint) {
int
len = A.size();
ListNode* h = new ListNode(A[
0
]);
if
(len ==
1
) {
h->next = h;
return
h;
}
else
{
ListNode* p = h;
for
(
int
i =
1
,k =
0
;i < len;i++) {
p->next =
new
ListNode(A[nextPoint[k]]);
p = p->next;
k = nextPoint[k];
}
}
return
h;
}
ListNode* insert(vector<
int
> A, vector<
int
> nxt,
int
val) {
ListNode* insertNode =
new
ListNode(val);
if
(A.empty()) {
insertNode->next = insertNode;
return
insertNode;
}
ListNode* head = buildLinkedList(A,nxt);
ListNode* p = head;
ListNode* q = head->next;
for
(
int
i =
1
; i < A.size(); i++) {
if
((val >= p->val && val <= q->val) || (val <= p->val && val >= q->val))
break
;
p = q;
q = q->next;
}
insertNode->next = q;
p->next = insertNode;
return
head;
}
};
解法:遍历链表,将链表分成两个子链表,其中一个链表的元素值都比阈值小,另一个比阈值都大,再将两个链表连接起来即可。
class
Divide {
ListNode* listDivide(ListNode* head,
int
val) {
if
(!head)
return
NULL;
if
(!head->next)
return
head;
ListNode *head1,*head2,*h1,*h2,*p,*q;
head1 = head2 = h1 = h2 = NULL;
p = head;
q = head->next;
while (p) {
if
(p->val <= val) {
if
(!head1) {
head1 = p;
h1 = head1;
}
else
{
h1->next = p;
h1 = h1->next;
}
}
else
{
if
(!head2) {
head2 = p;
h2 = head2;
}
else
{
h2->next = p;
h2 = h2->next;
}
}
p->next = NULL;
p = q;
if (q != NULL)
q = q->next;
}
if
(head1->val <= val) {
h1->next = head2;
if
(h2 != NULL)
h2->next = NULL;
return
head1;
}
else
{
h2->next = head1;
if
(h1 != NULL)
h1->next = NULL;
return
head2;
}
}
};
3、打印两个有序链表的公共部分
解法:同时遍历两个链表,逐个比较。相等则打印,两个指针同时后移;不相等则哪一个较小就将其对应指针后移,另一个指针不动;其中一个指针为空时停止比较。
class
Common {
public
:
vector<
int
> findCommonParts(ListNode* headA, ListNode* headB) {
vector<
int
> common;
if
(!headA || !headB)
return
common;
ListNode *p,*q;
p = headA;
q = headB;
while
(p && q) {
if
(q->val == p->val) {
common.push_back(q->val);
q = q->next;
p = p->next;
}
else
if
(q->val > p->val)
p = p->next;
else
q = q->next;
}