Given a linked list, removeNTh node from the end of list and return its head.
For example,
Given linked list: 1-> 2-> 3-> 4-> 5, andN= 2. After removing the second node from the end, the linked list becomes 1-> 2-> 3-> 5.
Note:
GivenNWill always be valid.
Try to do this in one pass.
The requirement is once... it seems that the foundation is still a little poor.
1. First, let's review the basic features of the linked list and analyze them from three points:
1> storage allocation method: the linked list stores the elements of a linear table with any group of storage units.
2> time performance: Search for O (n), insert, and delete. After a pointer is found, only O (1) is inserted and deleted ).
3> Space performance, no need to allocate storage space, as long as the need can be malloc, so it is also called a dynamic linked list.
4> node insertion and deletion icons:
2. Create a dynamic linked list (the leedcode linked list does not have a header node). The first parameter is a pointer. To change the pointer value, use a reference or pointer to the pointer.
Void CreateListHead (ListNode * & head, int n) {int j = 0; head = (ListNode *) malloc (sizeof (ListNode); head-> next = NULL; head-> val = v [j ++]; // v indicates the val ListNode * p = head of each node input by the user; for (int I = 1; I <n; ++ I) {ListNode * newNode; newNode = (ListNode *) malloc (sizeof (ListNode); p-> next = newNode; newNode-> next = NULL; newNode-> val = v [j ++]; p = p-> next ;}}
3. All debugging code
Vector <int> v; int num; struct ListNode {int val; ListNode * next; ListNode (int x): val (x), next (NULL ){}}; class Solution {public: int getLength (ListNode * head) {int length = 0; while (head) {++ length; head = head-> next;} return length ;} void deleteNode (ListNode * & head, int loc) // The first position is 1 {if (loc = 1) {head = head-> next ;} else {ListNode * p = head; int j = 1; while (p-> next & j <loc-1) {p = p-> next; ++ j ;} p-> next = p-> next;} ListNode * removeNthFromEnd (ListNode * head, int n) {if (head = NULL) return NULL; listNode * res = head; // you need to create a local variable int len = getLength (res); int loc = len-n + 1; deleteNode (res, loc ); return res ;}}; void CreateListHead (ListNode * & head, int n) {int j = 0; head = (ListNode *) malloc (sizeof (ListNode )); head-> next = NULL; head-> val = v [j ++]; ListNode * p = head; for (int I = 1; I <n; ++ I) {ListNode * newNode; newNode = (ListNode *) malloc (sizeof (ListNode); p-> next = newNode; newNode-> next = NULL; newNode-> val = v [j ++]; p = p-> next ;}} int main () {freopen ("C: \ Users \ Administrator \ Desktop \ a.txt "," r ", stdin); cin> num; for (int I = 0; I <num; ++ I) {int temp; cin> temp; v. push_back (temp);} ListNode * head = NULL; CreateListHead (head, 3); Solution so; ListNode * res = so. removeNthFromEnd (head, 1); return 0 ;}
Remove Nth Node From End of List (linked List)