您的位置:首页 > Web前端 > Node.js

Remove Duplicates from Sorted List && Merge Two Sorted Lists && Linked List Cycle && Remove Nth Node

2015-02-03 17:05 507 查看
Remove Duplicates from Sorted List

1、已排序的链表删除相同的数据。

ListNode *deleteDuplicates(ListNode *head) {
ListNode *p = head;
int temp;

while (p != NULL) {
temp = p->val;
ListNode *q = p->next;
if (q != NULL && q->val == temp) {
p->next = q->next;
free(q);
}
else
p = p->next;
}
return head;
}


Merge Two Sorted Lists

1、合并两个链表

ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if (l1 == NULL)
return l2;
else if (l2 == NULL)
return l1;
ListNode *head;
if (l1->val < l2->val) {
head = l1;
l1 = l1->next;
}
else {
head = l2;
l2 = l2->next;
}
ListNode *p = head;
while (l1 != NULL || l2 != NULL) {
if (l1 != NULL && (l2 == NULL || l1->val < l2->val)) {
p->next = l1;
p = p->next;
l1 = l1->next;
}
else {
p->next = l2;
p = p->next;
l2 = l2->next;
}
}
p->next = NULL;
return head;
}
2、这里也可以用递归的方法,代码会简洁很多。

Linked List Cycle

1、两个指针相差一的步进长度,往前走,如果相遇那么就是有环。

bool hasCycle(ListNode *head) {
if (head == NULL || head->next == NULL)
return false;
ListNode *p, *q;
p = q = head;
while (1) {
p = p->next;
q = q->next->next;
if (p == NULL || q == NULL || q->next == NULL)
return false;
if (p == q)
return true;
}
}


Swap Nodes in Pairs

1、交换链表中前后两个数据节点。

ListNode *swapPairs(ListNode *head) {
if (head == NULL || head->next == NULL)
return head;
ListNode *p = head;
ListNode *q = head->next->next;
head = p->next;
p->next->next = p;
p->next = q;

ListNode *temp;
while (q != NULL && q->next != NULL) {
p->next = q->next;
p = p->next;
temp = q;
q = q->next->next;
p->next = temp;
p = p->next;
}
p->next = q;
return head;
}


Linked List Cycle II
1、这里利用上面Linked List Cycle的函数,找到相遇点。

</pre><pre name="code" class="cpp">class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *p = findMeetPoint(head);
if (p != NULL) {
ListNode *q = head;
while (q != p) {
q = q->next;
p = p->next;
}
return q;
}
else
return NULL;
}
private:
ListNode *findMeetPoint(ListNode *head) {
if (head == NULL || head->next == NULL)
return NULL;
ListNode *p, *q;
p = q = head;
while (1) {
p = p->next;
q = (q->next)->next;
if (p == NULL || q == NULL || q->next == NULL)
return NULL;
if (p == q)
return p;
}
}
};


Remove Nth Node From End of List
1、两个指针,第一个先移动n个点。然后后面的指针就是要删除的点。

ListNode *removeNthFromEnd(ListNode *head, int n) {
ListNode *pre = head, *end = head;
while (n--)
end = end->next;
if (end == NULL) {
head = head->next;
free(pre);
return head;
}
while (end->next != NULL) {
pre = pre->next;
end = end->next;
}
ListNode *temp = pre->next;
pre->next = temp->next;
free(temp);
return head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: