Coding练习-1.单链表反转
struct ListNode{
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL){}
};
void ListNode_Pushback(ListNode** head, int value){
ListNode* newNode = new ListNode(value);
if (*head == NULL)
*head = newNode;
else{
ListNode* pNode = *head;
while (pNode->next != NULL)
pNode = pNode->next;
pNode->next = newNode;
}
}
void ListNode_Print(struct ListNode *head){
ListNode* pNode = head;
while(pNode!=NULL){
printf("%d\t",pNode->val);
pNode=pNode->next;
}
printf("\n");
}
void ListNode_Reverse(struct ListNode **data){
struct ListNode *head = *data;
struct ListNode *p = NULL;
struct ListNode *q = head->next;
while(q!=NULL){
head->next = p;
p = head;
head = q;
q = head->next;
}
head->next = p;
*data = head;
}
void test_linkrev()
{
struct ListNode *head=NULL;
for(int i=1;i<=4;i++)
ListNode_Pushback(&head,i);
ListNode_Print(head);
ListNode_Reverse(&head);
ListNode_Print(head);
}