链表测试程序
这里给了链表相关的基本操作。
链表结点结构体
struct ListNode{
int val;
ListNode *next;
Listnode(
int x) : val(x), next(NULL){}
};
给定数组即其元素个数创建链表
ListNode* createLinkedList(
int arr[],
int n){
if(n ==
0)
return NULL;
ListNode *head =
new ListNode(arr[
0]);
ListNode *curNode = head;
for(
int i =
1; i < n; i++){
curNode.next =
new ListNode(arr[i]);
curNode = curNode.next;
}
return head;
}
链表空间的释放
void deleteLinkedlist(ListNode *head){
ListNode *curNode = head;
while(curNode!=NULL){
ListNode *delNode = curNode;
curNode = curNode->next;
delete delNode;
}
}
打印链表
void printLinkedList(ListNode *head){
ListNode *curNode = head;
while(curNode!=NULL){
cout<< curNode->val <<
" -> ";
curNode = curNode->next;
}
cout <<
"NULL"<<endl;
return;
}
测试程序
int main() {
int arr[] = {
1,
2,
3,
4,
5};
int n =
sizeof(arr)/
sizeof(
int);
ListNode *head = createLinkedList(arr,n);
printLinkedList(head);
ListNode *head2 = reversedList(head);
printLinkedList(head);
deleteLinkedlist(head2);
return 0;
}