链表的几种构造方法
1.向前插入,如 3 –> 1,2,可以得到 3,1,2
ListNode *CreateList(int *a, int n)//构建一个长度为N的链表,两种构建方式中的一种
{
ListNode *head;
ListNode *rear;
head = NULL;
for (int i = 0; i < n; i ++)//后序插入3 -- 1,2 --> 3,1,2
{
rear = (ListNode *)malloc(sizeof(ListNode));
rear->val = a[i];
rear->next = head;
head = rear;
}
return head;
}
2.向后插入,如3–>1,2,得到1,2,3
ListNode *CreateList(int *a, int n)
{
ListNode *head = NULL;
ListNode *rear = NULL;
ListNode *move = head = (ListNode *)malloc(sizeof(ListNode));
for (int i = 0; i < n; i ++)
{
rear = (ListNode *)malloc(sizeof(ListNode));
rear->val = a[i];
rear->next = NULL;
move->next = rear;
move = move->next;
}
head = head->next;//去除头结点
return head;
}
3.反转链表
ListNode *reverseList(ListNode *head)
{
ListNode *pre;
ListNode *cur;
ListNode *next;
pre = NULL;
next = NULL;
cur = head;
while(cur)
{
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}