链表问题总结:
单链表逆置:
void TurnDlist(PDlist plist) {
assert(plist != NULL);
if (plist->head->next != NULL) {
DNode* curr = plist->head;
DNode* pre = NULL;
while (curr!= NULL) {
DNode* temp = curr->next;
curr->next = pre;
pre = curr;
curr = temp;
}
plist->head = pre;
}
}
判断单链表是否有环:
bool IsCycle(PDlist plist) {
assert(plist != NULL);
DNode* fast = plist->head;
DNode* slow = plist->head;
if (plist->head != NULL && plist->head->next != NULL) {
while (fast->next != NULL) {
fast = fast->next->next;
slow = slow->next;
if (fast == slow) {
return true;
}
}
return false;
}
else
{
return false;
}
}
有环找入口:
DNode* GetNode(PDlist plist) {
assert(plist != NULL);
if (IsCycle(plist)) {
DNode* fast = plist->head;
DNode* slow = plist->head;
while (fast->next != NULL) {
fast = fast->next->next;
slow = slow->next;
if (fast == slow) {
break;
}
}
if (fast == NULL || fast->next == NULL) {
return NULL;
}
fast = plist->head;
while (fast != slow) {
fast = fast->next;
slow = slow->next;
}
return fast;
}
}
两个单链表合并:
void MergeDlist(PDlist p1, PDlist p2) {
assert(p1 != NULL && p2 != NULL);
if (p1->head == NULL) {
p1->head = p2->head;
}
else {
DNode* curr = p1->head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = p2->head;
}
}
输出倒数第k个节点的值:
void PrintNode(PDlist plist, int k) {
assert(plist != NULL);
if (k <= 0 || plist->head == NULL) {
return;
}
else {
DNode* fast = plist->head;
DNode* slow = plist->head;
int count = 1;
while (count < k&&fast!=NULL) {
fast = fast->next;
count++;
}
if (fast == NULL) {
return;
}
else {
while (fast->next != NULL) {
fast = fast->next;
slow = slow->next;
}
printf("%d", slow->val);
}
}
}