typedef int SListDataType;
//链表中的一个节点
typedef struct Node{
SListDataType value; //值
struct Node *next; //下一个节点的地址
}Node;
//单链表
typedef struct SList{
Node *first;// *head 第一个节点的地址
} SList;
用前后指针,前面的指针先走
C写法:
SList* FindKLists(SList *head, int k){
Node* front = head;
Node* back = head;
int i;
for (i = 0; front != NULL && i < k; i++){//如果前k个还没有遍历完,fron就等于NULL了
front = front->next;
}
if (i < k){//如果只有5个数,k却是7,所以找到的结果就为空
return NULL;
}
while (front != NULL){
front = front->next;
back = back->next;
}
return back;
}
JAVA写法:
public class Nowcoder {
public class ListNode{
int val;
ListNode next=null;
ListNode(int val){
this.val=val;
}
}
public class Partition {
public ListNode partition(ListNode pHead,int k) {
ListNode front = pHead;
ListNode back = pHead;
int i;
for ( i = 0; front != null && i < k; i++){//如果前k个还没有遍历完,fron就等于NULL了
front = front.next;
}
if (front==null&&i < k){//如果只有5个数,k却是7,所以找到的结果就为空
return null;
} else if(front==null){//只有六个数,k也是6
return pHead;
}
while (front != null){
front = front.next;
back = back.next;
}
return back;
}
}
}