本文主要是介绍链表创建及反转,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>#define MAXSIZE 128
#define SIZE 10typedef struct ListNode* List;struct ListNode{int val;struct ListNode* next;
};List CreateList1(List head, int *data, int size) {//头插法List p;int i;head->next = NULL;for(i = 0; i < size; i++){p = (List)malloc(sizeof(struct ListNode));p->val = data[i];p->next = head->next;head->next = p;}return head;
} List CreateList2(List head, int *data, int size) {//尾插法 int i;List p, q;p = q = head;for(i = 0; i < size; i++) {p = (List)malloc(sizeof(struct ListNode));p->val = data[i];q->next = p;q = p;}q->next = NULL;return head;
}List ReverseList(List head) {List last = NULL, next = NULL, p;p = head->next;while(tmp) {next = p->next;p->next = last;last = p;p = next;}head->next = last;return head;
}void PrintList(List head) {List t = head->next;while(t) {printf("%d\t", t->val);t = t->next; }printf("\n");
}int main(void)
{List list;int data[SIZE], i;for(i = 0; i < SIZE; i++) {data[i] = i;}list = (List)malloc(sizeof(struct ListNode));list->next = NULL;list = CreateList2(list, data, SIZE);PrintList(list);printf("list reverse...\n");list = ReverseList(list);PrintList(list);return 0;
}
这篇关于链表创建及反转的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!