#include<iostream> class ListNode { public: int val; ListNode *prev; ListNode *next; ListNode(int x) : val(x), prev(NULL), next(NULL) {}
voidappend_to_tail(int v); }; void ListNode::append_to_tail( int v ) { ListNode* end = new ListNode(v); ListNode* node(this); if (!node) return; while (node->next) { node = node->next; } end->prev = node; node->next = end; } ListNode* insert_node_to_pos(ListNode* head, int pos, int val) { intdef_pos(pos-1); if (!head) returnnew ListNode(val); // empty head if (!def_pos) // insert to head { ListNode* newhead = new ListNode(val); newhead->next = head; head->prev = newhead; return newhead; } ListNode* node(head); while (node->next) { if (def_pos == 1) { ListNode* newnode = new ListNode(val); newnode->next = node->next; node->next = newnode; newnode->prev = node; newnode->next->prev = newnode; return head; // head didn't change } node = node->next; --def_pos; } if (def_pos != 1) head->append_to_tail(val); return head; } ListNode* delete_node(ListNode* head, int val) { if (!head) returnNULL; if (head->val == val) { head->next->prev = NULL; return head->next; // moved head } ListNode* node(head); while (node->next) { if (node->next->val == val) { node->next = node->next->next; node->next->prev = node; return head; // head didn't change } node = node->next; } return head; } voidprint_list(ListNode* head) { std::cout << "List: " << std::endl; ListNode* end(NULL); while (head) { if (!head->next) {end = head;} std::cout << head->val << " "; head = head->next; } std::cout << std::endl; while (end) { std::cout << end->val << " "; end = end->prev; } std::cout << std::endl; } intmain() { // test NULL std::cout << "-----Test NULL-----" << std::endl; ListNode* head = NULL; print_list(head); head = delete_node(head, 0); print_list(head); head = insert_node_to_pos(head, 1, 1); print_list(head); // test head std::cout << "-----Test head-----" << std::endl; print_list(head); head = insert_node_to_pos(head, 1, 2); print_list(head); head = delete_node(head, 2); print_list(head); // test not exist std::cout << "-----Test not exist-----" << std::endl; print_list(head); head = insert_node_to_pos(head, 10, 3); print_list(head); head = delete_node(head, 5); print_list(head); // test normal std::cout << "-----Test normal-----" << std::endl; head->append_to_tail(4); head->append_to_tail(5); head->append_to_tail(6); head->append_to_tail(7); print_list(head); head = insert_node_to_pos(head, 3, 50); print_list(head); head = delete_node(head, 50); print_list(head); system("Pause"); };
快慢指针技巧(The “Runner” Technique)
The “runner” (or second pointer) technique means that you iterate through the linked list with two pointers simultaneously, with one ahead of the other. The “fast” node might be ahead by a fixed amount, or it might be hopping multiple nodes for each one node that the “slow” node iterates through.