數據結構:數據結構
typedef int DataType; typedef struct Node { DataType data; struct Node *next; }Node,* LinkList;
一、從尾到頭打印單鏈表ide
void TailToFrontPrint(LinkList head) /*從尾到頭打印單鏈表*/ { if (head != NULL) { TailToFrontPrint(head->next); printf("%d ", head->data); } }
二、刪除一個無頭單鏈表的非尾結點it
void DelNoneTailNode(Node *pos) /*刪除一個無頭單鏈表的非尾結點*/ { assert(pos); if (pos->next == NULL) { return; } Node *del = pos->next; pos->data = del->data; pos->next = del->next; free(del); del = NULL; }
三、在無頭單鏈表的一個非頭結點前插入一個結點ast
void InsNoneFrontNode(Node *pos,DataType x) /*在無頭單鏈表的一個非頭結點前插入一個結點*/ { Node *s = (Node *)malloc(sizeof(Node)); s->data = pos->data; pos->data = x; s->next = pos->next; pos->next = s; }
四、逆置/反轉單鏈表class
void ReverseNode(LinkList &head) /*反轉單鏈表*/ { Node *front = NULL; Node *tmp = head; Node *start = NULL; while (tmp != NULL) { start = tmp->next; tmp->next = front; front = tmp; tmp = start; } head = front; }
五、查找單鏈表的中間節點,要求只遍歷一次鏈表List
Node * FindMidNode(LinkList head) /*查找單鏈表的中間結點*/ { Node *slow = head; Node *fast = head; while (fast && fast->next) { fast = fast->next->next; if (fast == NULL) /*有if偶數時返回較小,無if返回較大*/ { break; } slow = slow->next; } return slow; }
六、查找單鏈表的倒數第k個結點,要求只遍歷一次鏈表遍歷
Node * FindKNode(LinkList head, int k) /*返回倒數第k個結點*/ { assert(head); /*一、k大於head的長度 二、*/ Node *slow = head; Node *fast = head; while (k--) { if (fast == NULL) { return NULL; } else { fast = fast->next; } } while (fast) { slow = slow->next; fast = fast->next; } return slow; }