//recursion链表倒置法1 Node * reverse(Node * head) { if(head == NULL || head->next == NULL) return head; Node * q = head->next; //先翻转head->next Node * newHead = reverse(head->next); q->next = head; head->next = NULL; return newHead; } //non-recursion链表倒置法2 Node * reverse(Node * head) { if(head == NULL || head->next == NULL) return head; Node *p1,*p2,*p3; p1 = head; p2 = head->next; while(p2 != NULL) { p3 = p2->next; p2->next = p1; p1 = p2; p2 = p3; } head->next = NULL; head = p1; return head; }
//链表的插入操作 typedef struct Node { int value; Node *next; Node(int v) { value = v; next = NULL; } Node() { next =NULL; } }Node,*Ptr; //由小到大插入链表 Node* insert(Node *head,int value) { Node *node = new Node(value); if(head == NULL) //头结点不存在时 { return node; } if(head->value > value)//value小于当前head->value时 { node->next = head; head->next = NULL; return head; } Node *tmp = head; while(tmp != NULL) { if(tmp->value < value) { if(tmp->next == NULL) { tmp->next = node; break; } else { tmp = tmp->next; } } else { node->next = tmp->next; tmp->next = node; break; } } return head; }