链表相关LeetCode
对于LeetCode上的链表相关题目,若想在本地测试运行,需要添加代码。
本地输出链表
- Python
# Definition for singly-linked list.
class ListNode:
def __init__(self,val):
self.val = val
self.next = None
class LinkList:
def __init__(self):
self.head = None
def headList(self,data):
dummy = ListNode(-1)
cur = dummy
for i in data:
node = ListNode(i)
cur.next = node
cur = cur.next
return dummy.next
def printList(self,head):
if head == None: return
cur = head
while cur:
print(cur.val)
cur = cur.next
- C++
#include <iostream>
using namespace std;
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* cur = head;
for (int i=1;i<n;i++){
cur->next = new ListNode(arr[i]);
cur = cur->next;
}
return head;
}
void printListNode(ListNode* head){
ListNode* cur = head;
while (cur){
cout << cur->val << "->";
cur = cur->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);
printListNode(head);
return 0;
}