Idea 1: Two pointers P1, p2, p1 traverse from the beginning, when the P1 reaches the K-node, p2 begins; When P1 reaches the last node in the list, p2 refers to the node in the list that is the reciprocal K-node.
Public classnode{ Public intdata; PublicNode Next; PublicNode (intdata) { This. data =data; } PublicNode Removelastknode (node head,intk) { if(Head = =NULL|| K < 1){ returnHead; } Node p1=Head; Node P2=Head; intnum = 1; while(P1.next! =NULL&& Num <k) { ++num; P1=P1.next; } while(P1.next! =NULL) {P1=P1.next; P2=P2.next; } P2.next=P2.next.next; returnHead; }}
Train of thought 2: Time complexity O (n), Spatial complexity O (1).
1> If the linked list is empty or K < 1, return directly;
2> chain list from head to tail, each move one step, k value minus 1;
3> k > 0, there is no reciprocal K-node, return to the entire list;
If k = 0, the head node is the reciprocal K-node, and the head pointer is returned;
If k < 0, go from the beginning to find the node to delete the previous node, each move to let the K value plus 1, when k=0, the pointer value to the node is to delete the node of the previous node.
PublicNode Removelastkthnode (node head,intlastkth) { if(Head = =NULL|| Lastkth < 1){ returnHead; } Node P=Head; while(P! =NULL) {lastkth--; P=P.next; } if(lastkth = = 0) {Head=Head.next; } if(Lastkth < 0) {p=Head; while(++lastkth! = 0) {p=P.next; } P.next=P.next.next; } returnHead; }
Delete the penultimate K node in a single-linked list