listNode.h
#pragma once
#include <stdio.h>
struct node
{
int i;
struct node* next;
};
//新增一個鏈表節點
void addListNode(struct node* head, int idata);
//打印鏈表節點
void printListNode(struct node* head);
//反序
struct node* reverseOrderListNode(struct node* head);
//創建一個頭的鏈表節點
struct node* createHeadNode(int idata);
listNode.cpp
#include "listNode.h"
#include "malloc.h"
int addNode(int iData)
{
return 1;
}
struct node* createHeadNode(int idata)
{
struct node* head = (struct node*)malloc(sizeof(struct node));
if (head)
{
head->i = idata;
head->next = NULL;
}
return head;
}
void addListNode(struct node*head, int idata)
{
struct node* pTemp = head;
while(NULL != pTemp->next)
{
pTemp = pTemp->next;
}
pTemp->next = (struct node*)malloc(sizeof(struct node));
pTemp->next->i = idata;
pTemp->next->next = NULL;
}
void printListNode(struct node*head)
{
printf("\n");
struct node* temp = head;
while (temp)
{
printf("%d ", temp->i);
temp = temp->next;
}
printf("\n");
}
//把head的next(p1) 放入head的前面,head=p1,
struct node* reverseOrderListNode(struct node*head)
{
if (NULL == head)
{
return head;
}
struct node* p2 = head->next;
head->next = NULL;
struct node* p1 = head;
struct node* p3 = NULL;
while (p2)
{
p3 = p2->next;
p2->next = p1;
head = p2;
p1 = p2;
p2 = p3;
}
printf("%d ", head->i);
return head;
// printListNode(head);
}
測試的
void testNodeList()
{
struct node* head = createHeadNode(0);
addListNode(head, 1);
addListNode(head, 2);
addListNode(head, 3);
addListNode(head, 4);
printListNode(head);
head = reverseOrderListNode(head);
printListNode(head);
}
int main()
{
testNodeList();
}
測試結果:
0 1 2 3 4
4 3 2 1 0
容易的錯誤:一個指針的如果可能被改變,那麼在傳入實參的時候一定要注意,
要麼實參是指針的指針;要麼返回修改的指針
struct node* reverseOrderListNode(struct node*head)