Connected to the basic operation of a single-linked list, I have organized a number of linked list frequently tested topics, and constantly updated in ...
1. Find the penultimate K node in the list and delete the last K nodes
//give two pointers p and Q, let one of the pointer p lead the Q pointer k step,//Then move the p and Q pointers at the same time, when the leading pointer p reaches the end of the list first, the node that follows the pointer Q points to exactly the penultimate node. Node*Getkthnode (int k) {Node*P=Head Node*Q=Head while(k>1&&P -Next!=NULL) {P=P -Next K--; }if(k>1||P==NULL)return NULL; while(p -Next!=NULL) {Q=Q -Next P=P -Next }returnQ;}//Delete K-nodes from the bottom of the pageNode*Delkthnode (int k) {Node*P=Head Node*Q=Head while(k>1&&P -Next!=NULL) {P=P -Next K--; }if(k>1||P==NULL)return NULL; Node*Pre=Q//Record the previous node that needs to be deleted while(p -Next!=NULL) {Pre=Q Q=Q -Next P=P -Next } Pre -Next=Q -NextreturnHead;}
2. Finding the middle node of a linked list
//Given two pointers p and Q, let the P pointer take two steps while the Q pointer goes one step. When the P pointer is pointing at the end or the previous node at the end, the median value is evaluated.//If the list length is odd, the node of q is the middle node, and if the list length is even, the node of Q is the first of the two nodes in the middle (we let it return to the previous node). int Getmid () {if(Head==NULL||Head -Next==NULL)return 0;if(Head -Next -Next==NULL)returnHead -Data; Node*P=Head Node*Q=Head while(p -Next!=NULL&&P -Next -Next!=NULL) {P=P -Next -Next Q=Q -Next }returnQ -Data;}
3. Time complexity in O (1) Delete a node specified in a single linked list
//For deleting a node, our common idea is to have the node's previous node point to the node's next node//This situation requires traversing the previous node to find the node with a time complexity of O (n). For linked lists,each node structure in the list is the same, so we can copy the data from the next node of the node to that node //Then delete the next node. To pay attention to the situation of the last node, this time can only be used in a common way to operate, first find the previous node, but the overall average time complexity is still O (1)voidDelnode (Node*Head,node*Todelete) {if(Head==NULL)return;if(Head -Next==NULL) head=NULL;Else{if(Todelete -Next!=NULL)//Not tail node to delete{Todelete -Data=Todelete -Next -Data; Todelete -Next=Todelete -Next -Next }Else{Node*Node=Head while(node -Next!=Todelete) node=Node -Next Node -Next=NULL; } }}
4. Print a single linked list from the end of the head
//从尾到头打印节点void reversePrintLink(){ if(head==NULL) return; stack<int> s; Node* p=head; while(p!=NULL) { s.push(p->data); p=p->next; } int value=0; while(!s.empty()) { value = s.top();//不能直接用pop()赋值,pop返回的是void类型 s.pop(); cout<<value<<" "; } cout<<endl;}
Common operation of single-linked list (II.)