首页 > 代码库 > 单链表
单链表
#include "stdafx.h"#include "stdlib.h"typedef struct Node{ int data; struct Node* next;} LinkNode;void PrintNodes(LinkNode *&List){ LinkNode *p = NULL; if (!List) return; p = List->next; while (p) { printf("%d ", p->data); p = p->next; } printf("\n");}void CreateLinkList(LinkNode *&List){ if (List) return; List = (LinkNode*)malloc(sizeof(LinkNode)); if (!List) return; List->next = NULL; List->data = http://www.mamicode.com/0;}void AddNode(LinkNode *&List, int data){ LinkNode *p = NULL; LinkNode *node = NULL; if (!List) return; node = (LinkNode*)malloc(sizeof(LinkNode)); if (!node) return; node->data =http://www.mamicode.com/ data; p = List; while (p->next) { p = p->next; } node->next = p->next; p->next = node;}void MoveNodeByData(LinkNode *&List, int data){ LinkNode *p = NULL; LinkNode *q = NULL; if (!List) return; p = List; while (p->next) { q = p->next; if (q->data =http://www.mamicode.com/= data) { p->next = q->next; free(q); break; } p = p->next; } }void MoveNodeByPos(LinkNode *&List, int pos){ int n = 0; LinkNode *p = NULL; LinkNode *q = NULL; if (NULL == List || NULL == List->next) return; p = List; while (p->next) { q = p->next; n++; if (n == pos) { p->next = q->next; free(q); break; } p = p->next; } }int GetLength(LinkNode *&List){ int length = 0; LinkNode *p = NULL; if (!List) return 0; p = List->next; while (p) { length++; p = p->next; } return length;}void ReverseNodes(LinkNode *&List){ LinkNode *p = NULL; LinkNode *q = NULL; p = List->next; List->next = NULL; while (p) { q = p->next; p->next = List->next; List->next = p; p = q; }}void SortNodes(LinkNode *&List){ LinkNode *p; int i, j; int temp = 0; int length = GetLength(List); if (NULL == List || NULL == List->next) return; for (i = length-1; i >= 0; i--) { p = List->next; for (j = 0; j < i; j++) { if (p->data > p->next->data) { temp = p->data; p->data = http://www.mamicode.com/p->next->data; p->next->data =http://www.mamicode.com/ temp; } p = p->next; } }}int main(void){ LinkNode *List = NULL; CreateLinkList(List); AddNode(List, 10); AddNode(List, 8); AddNode(List, 3); AddNode(List, 7); AddNode(List, 2); AddNode(List, 1); AddNode(List, 5); AddNode(List, 3); AddNode(List, 4); AddNode(List, 9); PrintNodes(List); ReverseNodes(List); PrintNodes(List); MoveNodeByPos(List, 10); PrintNodes(List); SortNodes(List); PrintNodes(List); return 0;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。